Insert a new value in a tree python

回眸只為那壹抹淺笑 提交于 2021-01-07 02:33:19

问题


I have an tree like:

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.

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.

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]

Thanks in advance


回答1:


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.




回答2:


Since you mentioned recursion, here's a solution using recursion:

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)

Testing the solution:

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)

The function traverses the tree recursively until reaching the correct place to insert the node. Since it is a Binary search tree, we must ensure the condition that any child to the left of a node should be less than that node, and any child to the right should be greater. Thats why we go lef/right according to the comparison of the new node with the current root of the traversal.



来源:https://stackoverflow.com/questions/64982694/insert-a-new-value-in-a-tree-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!