我正在尝试创建一个 python 二叉树实现。我相信我已经正确地创建了插入方法,但是我在使用中序遍历打印树时遇到了问题。
我正在努力研究如何正确打印二叉树的每个实例。这是我到目前为止所拥有的。任何帮助,将不胜感激。谢谢。
class BinaryTree():
def __init__(self,rootid):
self.left = None
self.right = None
self.rootid = rootid
def insert(self, item):
if item < self.rootid:
if self.left is None:
self.left = BinaryTree(item)
else:
self.left.insert(item)
else:
if self.right is None:
self.right = BinaryTree(item)
else:
self.right.insert(item)
def inorder_print(self):
if self.left:
print(self.left)
print (self.rootid)
if self.right:
print(self.right)
tree = BinaryTree(5)
while True:
answer = input("Do you wish to add a value to the tree? ")
if answer == "y":
item = int(input("Please enter your number: "))
tree.insert(item)
else:
break
tree.inorder_print()
最佳答案
你的顺序打印功能似乎有误。
对于顺序打印,您需要对左树递归调用 inorder_print()
,然后打印当前根,然后对右树执行相同的递归操作。
例子-
def inorder_print(self):
if self.left:
self.left.inorder_print()
print (self.rootid)
if self.right:
self.right.inorder_print()
关于Python二叉树实现插入方法: help required,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31244145/