我打算像here一样进行二叉树搜索。我有一个问题是正确设置节点。
问题: 当应该创建新节点时,根节点似乎被覆盖。第一次
Bintree.put(newValue)
被称为在Bintree.root中创建的新节点。第二次,根节点似乎在函数调用Bintree.put(newValue)中被覆盖。
以下这些行在执行时是否会更改根节点?
node = root
node = node.left # Left is a node below node
node = Node()
下面的行是我的程序的代码。
# Node for binary tree
class Node():
def __init__(self):
self.data = None
self.left = None
self.right = None
class Bintree:
def __init__(self):
self.root = None
def put(self, newvalue):
'''Sends the new value into the correct position in the Bintree
:param newvalue: The data that's sent to storage'''
self.root = push(self.root, newvalue)
def push(root, value):
# This function puts the value in the correct position in the bintree
# Not to be used by user.
node = root
while node is not None:
if node.data < value:
node = node.left
else:
node = node.right
node = Node()
node.value = value
return node
答案 0 :(得分:2)
是的,你说得对,我把它拧了一下。
class Node(): def init(self): self.data = None self.left = None self.right = Noneclass Bintree: def init(self): self.root = None
def put(self, newvalue): '''Sends the new value into the correct position in the Bintree :param newvalue: The data that's sent to storage''' if self.root is None: self.root = Node() self.root.data = newvalue else: self.push(self.root, newvalue) def push(self, node, value): # This function puts the value in the correct position in the bintree # Not to be used by user. if value < node.data: if node.left is not None: self.push(node.left,value) else: node.left = Node() node.left.data = value else: if node.right is not None: self.push(node.right,value) else: node.right = Node() node.right.data = value
我是从头开始用递归做的。它更简单。 当然它没有用,因为在你的第一次尝试中你总是将root设置为none,而在第二次你只是一直更新root(我的坏)