二叉树改变根

Binary tree changing root

开始研究二叉树,在教学网站上找到这段代码

class Node:

    def __init__(self, data):

        self.left = None
        self.right = None
        self.data = data

    def insert(self, data):
# Compare the new value with the parent node
        if self.data:
            if data < self.data:
                if self.left is None:
                    self.left = Node(data)
                else:
                    self.left.insert(data)
            elif data > self.data:
                if self.right is None:
                    self.right = Node(data)
                else:
                    self.right.insert(data)
        else:
            self.data = data

# Print the tree
    def PrintTree(self):
        if self.left:
            self.left.PrintTree()
        print( self.data),
        if self.right:
            self.right.PrintTree()

# Use the insert method to add nodes
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(31)
root.insert(10)
root.insert(19)


root.PrintTree()

在调试上述代码后,我注意到在开始时设置了正确的根值,但在几步之后更改为另一个值。 最后,根值设置为正确的 int(第一个值),但我不明白为什么。

此外,是否有更好的方法来创建二叉树并在 python 中插入值?

我认为你被调试器愚弄了。在前三个语句之后,您将拥有三个对象:一个名为 root,一个名为 root.left,一个名为 root.right:

root.data = 27
root.left.data = 14
root.right.data = 35

如果您随后通过插入 31 进行跟踪,您将到达 insert 中调用 self.right.insert(data) 的部分。届时,您将再次开始 insert,但现在 selfroot.right 中的节点。不再是 root