Python二叉树实现插入方法: help required

标签 python tree binary-tree

我正在尝试创建一个 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/

相关文章:

java - 打印哈夫曼树中的正确路径

python - 在不调用 bzr 的情况下从 Python 确定 Bazaar 版本号

python - 您可以将带有参数的函数存储在列表中,然后在 Python 中调用它们吗?

将二叉树转换为其镜像树的 C 函数

C++ 二叉搜索树通过递归插入

c - 如何在C中搜索枚举类型

python - VS Code/Python/使用调试器调试 pytest 测试

python - 将某一列中的行值与其他列中的值进行比较

将有序树转换为有向无环图的算法

Python:从树状数据结构中的列表列表创建组合