Python 二叉树实现插入方法:需要帮助
Python Binary Tree Implementation insert method: help required
我正在尝试创建一个 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
需要是一个递归函数:它需要遍历其子项并打印每个子项。因此,您需要调用 self.left.inorder_print()
.
而不是仅仅执行 print(self.left)
你的订单打印功能好像有误
对于顺序打印,您需要对左树递归调用inorder_print()
,然后打印当前根,然后对右树执行相同的递归。
例子-
def inorder_print(self):
if self.left:
self.left.inorder_print()
print (self.rootid)
if self.right:
self.right.inorder_print()
我正在尝试创建一个 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
需要是一个递归函数:它需要遍历其子项并打印每个子项。因此,您需要调用 self.left.inorder_print()
.
print(self.left)
你的订单打印功能好像有误
对于顺序打印,您需要对左树递归调用inorder_print()
,然后打印当前根,然后对右树执行相同的递归。
例子-
def inorder_print(self):
if self.left:
self.left.inorder_print()
print (self.rootid)
if self.right:
self.right.inorder_print()