在树中插入一个新值 python

Insert a new value in a tree python

我有这样一棵树:

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

数字代表每个节点的根,none代表没有值的children。

例如主根是4,[[None,1,None],2,[None,3,None]]是左边的子树和这个 [None,6,[None,7,None]] 是右边的子树。左边子树的主根是2 etc etc...

我的问题是我想在此树中插入一个值。

比如我要加值5,这是我要的:

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

我的函数有两个参数,树和要相加的整数,我需要使用递归函数,例如这是我开始的:

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

提前致谢

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

# 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)

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

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

预序和post序遍历也适用。

既然你提到了递归,这里有一个使用递归的解决方案:

def insert_node(root, node):
    if root == [None]:  #corner case of an empty tree
        root.append(node)
        root.append(None)   #now root will be : [None, node, None]
        return
    if node <= root[1]:  #we need to go left
        if root[0] == None:
            root[0] = [None, node, None]
            return
        else:
            insert_node(root[0], node)
    else:               #we need to go right
        if root[2] == None:
            root[2] = [None, node, None]
            return
        else:
            insert_node(root[2], node)

测试解决方案:

tree = [None]   #starting with an empty tree
insert_node(tree, 4)
insert_node(tree, 2)
insert_node(tree, 1)
insert_node(tree, 3)
insert_node(tree, 6)
insert_node(tree, 7)
print(tree)

函数递归遍历树,直到到达正确的位置插入节点。既然是二叉搜索树,那么我们就必须保证一个节点左边的任意child都应该小于那个节点,右边的任意一个child都应该大于这个节点。这就是为什么我们根据遍历的新节点与当前根的比较lef/right