在树python中插入新值 [英] Insert a new value in a tree python

查看:128
本文介绍了在树python中插入新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一棵像这样的树

tree = [[[None,1,None],2,[None,3,None]],4,[None,6,[None,7,None]]]

数字代表每个节点的根,无代表没有值的子代.

The numbers represent the root of each node, the none represent the children that have no value.

例如,主根是4,[[None,1,None],2,[None,3,None]]是左侧的子树,而该[None,6,[None,7,无]]是他在右侧的子树.左侧子树上的主要根是2,依此类推...

For example, the main root is 4 and [[None,1,None],2,[None,3,None]] is the sub tree on the left and this [None,6,[None,7,None]] is he sub tree on the right. The principal root on the sub tree on the left is 2 etc etc...

我的问题是我想在这棵树中插入一个值.

And my problem is that I want to insert a value in this tree.

例如,我想要添加值5,这就是我想要的:

For example I want to add the value 5, this is that I want:

tree = [[[None, 1, None], 2, [None, 3, None]], 4, [[None, 5, None], 6, [None, 7, None]]]

我的函数需要两个参数,即树和要添加的整数,我需要使用递归函数,例如,这就是我开始的内容:

My function takes two arguments, the tree and the integer to add, I need to use recursive function, for example this is what i started:

def insert(tree,int):
    cur = tree
    prev = None
    while cur != None:
        prev = cur
        if int < cur[1]:
            cur = cur[0]
        else :
            cur = cur[2]

预先感谢

推荐答案

这可以通过遍历树来找到目标节点并将其元素替换为所需的值来完成.

This can be done by doing a tree traversal to find the target node and replace its element with the desired value.

# Do an in-order traversal recursively
def in_order(tree):
    if tree is None:
        return
    for element in in_order(tree[0]):
        yield element
    yield tree
    for element in in_order((tree[2])):
        yield element

# helper method to create a new node
def new_node(val):
    return [None, val, None]

if __name__ == '__main__':
    tree = [[[None, 1, None], 2, [None, 3, None]], 4, [None, 6, [None, 7, None]]]
    print(tree)
    # Search for the target node with the value 6 and create a new node as its left child 
    for element in in_order(tree):
        if element[1] == 6:
            element[0] = new_node(5)
    print(tree)

由于遍历树是访问树中所有节点的通用方法,因此可以对其进行修改以查找其他节点. 例如:

As tree traversal is a universal way to access all the nodes in the tree, it can be modified to find other nodes. For example:

# Finding leaf nodes
for element in in_order(tree):
    if element[0] is None and element[2] is None:
        # Do something
        pass

预订遍历和订单遍历也适用.

Pre-order and post-order traversal are also applicable.

这篇关于在树python中插入新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆