用于插入BST的递归代码不起作用

时间:2019-09-08 12:44:37

标签: python recursion binary-search-tree insertion

我正在尝试插入新节点以形成BST(二进制搜索树)。 我尝试使用递归编写插入函数,但是插入似乎不起作用

class Node():
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def insert(root, node):
    if root is None:
        root = node
    else:
        if (root.data < node.data) :
            insert(root.right, node)
        else:
            insert(root.left, node)

### Driver code
r = Node(50) 
insert(r,Node(30)) 
insert(r,Node(20)) 
insert(r,Node(40)) 
insert(r,Node(70)) 
insert(r,Node(60)) 
insert(r,Node(80)) 

以上插入无效!子节点仍然为None,并且不采用插入的Node值。 但是,如果我尝试修改上述insert方法以在每个递归步骤中返回“ root”,则插入似乎可以正常工作。

def insert(root, node):
    if root is None:
        return node
    else:
        if (root.data < node.data) :
            root.right = insert(root.right, node)
        else:
            root.left = insert(root.left, node)
        return root

可以解释为什么即使在做完全相同的事情时这两种情况下的行为也不同吗? 谢谢

0 个答案:

没有答案