我想在二进制搜索树中插入一个“新”节点。但是在运行代码时,我遇到了诸如以下错误:
an infinte loop (with nothing as display)
temp.data(nonetype) has no value.
您能看到这段代码中的错误是什么以及如何纠正该错误。
请参阅我的以下代码:
class Node:
def __init__(self,data=0):
self.data = data
self.left = None
self.right = None
class tree:
def __init__(self):
self.root = None
def insert(self,data):
temp = root
new_node = Node(data)
new_node.left = None
new_node.right =None
while temp.left and temp.right:
if new_node.data < temp.data:
temp = temp.left
else:
temp = temp.right
if temp.data > new_node.data:
temp.left = new_node
else:
temp.right = new_node
def display(self,temp):
if temp == None:
return
else:
print(temp.data,end = " ")
self.display(temp.left)
self.display(temp.right)
if __name__=='__main__':
mylist = tree()
root = Node(19)
root.left =Node(12)
root.right = Node(30)
mylist.insert(10)
mylist.display()
答案 0 :(得分:0)
当节点只有左或右子树时,将不考虑您的代码。在遍历节点时,您需要检查您的左孩子或右孩子是否为None类型。
我修改了树类以初始化构造函数中的root。
修改后的代码:
class Node:
def __init__(self,data=0):
self.data = data
self.left = None
self.right = None
class tree:
def __init__(self,root):
self.root = root
def insert(self,data):
temp = self.root
new_node = Node(data)
new_node.left = None #remove this as it will be set to none in Node constructor itself.
new_node.right =None #remove this
while temp.left or temp.right:
if new_node.data < temp.data:
if temp.left != None:
temp = temp.left
else:
break
else:
if temp.right !=None:
temp = temp.right
else:
break
if temp.data > new_node.data:
temp.left = new_node
else:
temp.right = new_node
def display(self,temp):
if temp == None:
return
else:
print(temp.data,end = " ")
self.display(temp.left)
self.display(temp.right)
if __name__=='__main__':
root = Node(19)
#root.left =Node(12) #insert using insert function of tree class
#root.right = Node(30)
mylist = tree(root)
mylist.insert(12)
mylist.insert(30)
mylist.insert(10)
mylist.insert(20)
mylist.insert(18)
mylist.insert(9)
mylist.display(root)