python - 如何在 python 中打印二叉搜索树?

标签 python data-structures

下面是一个二叉搜索树,它有一个根节点、一个左节点和一个右节点。 该代码有效,但我想显示此二叉搜索树,以便我可以看到层中的每个节点... 这是代码...

class Node:
    def __init__(self,value):
        self.value = value
        self.left = None
        self.right = None

class Binary_search_tree:
    def __init__(self):
        self.root=None

    def insert(self,value):
        if self.root==None:
            self.root=Node(value)
        else:
            self.insert_after_root(value)

    def insert_after_root(self, value):
        if value > self.root.value:
            self.root.left = Node(value)
        elif value < self.root.value:
            self.root.right = Node(value)

bst = Binary_search_tree()
bst.insert(4)
bst.insert_after_root(2)
bst.insert_after_root(8)

最佳答案

你的实现有一些问题:

  • 树只能有 3 个节点,因为您永远不会创建根的孙节点,而总是使新节点成为根或其子节点之一

  • 左/右颠倒:您应该在左侧插入较小的值。

  • 在主程序代码中,您应该只使用insert方法,而不要使用insert_after_root

这是基于递归(在 Node 上放置一个方法)对您的实现进行的更正,以及一组用于生成字符串表示的附加方法,倾斜 90°(显示根在左边)。

class Node:
    def __init__(self,value):
        self.value = value
        self.left = None
        self.right = None

    def insert_after(self, value):
        if value < self.value:
            if self.left:
                self.left.insert_after(value)
            else:
                self.left = Node(value)
        elif value > self.value:
            if self.right:
                self.right.insert_after(value)
            else:
                self.right = Node(value)
        else:
            raise ValueError("this tree doesn't accept duplicates")

    def __repr__(self):
        lines = []
        if self.right:
            found = False
            for line in repr(self.right).split("\n"):
                if line[0] != " ":
                    found = True
                    line = " ┌─" + line
                elif found:
                    line = " | " + line
                else:
                    line = "   " + line
                lines.append(line)
        lines.append(str(self.value))
        if self.left:
            found = False
            for line in repr(self.left).split("\n"):
                if line[0] != " ":
                    found = True
                    line = " └─" + line
                elif found:
                    line = "   " + line
                else:
                    line = " | " + line
                lines.append(line)
        return "\n".join(lines)


class Binary_search_tree:
    def __init__(self):
        self.root=None

    def insert(self,value):
        if self.root==None:
            self.root=Node(value)
        else:
            self.root.insert_after(value)

    def __repr__(self):
        return repr(self.root)

bst = Binary_search_tree()
bst.insert(4)
bst.insert(2)
bst.insert(8)
bst.insert(3)
bst.insert(5)
bst.insert(7)
bst.insert(10)

print(str(bst))

关于python - 如何在 python 中打印二叉搜索树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62406562/

相关文章:

arrays - 最大化数组中的反转计数

python - PowerShell:从 Azure Blob 存储运行 Python 脚本

python - 如何从 python 列表中只删除零位?

python - 如何使用python将数据写入excel文件而不更改原始文件中的格式单元格?

python - PyQt中的无限背景while循环

java - 这个不相交集数据结构的构造函数?

java - 估计算法运行时间的增长顺序

perl - 确定日期范围内的日期的好方法是什么?

python - 当依赖项更改时, 'intelligently' 在 Python 中重置记忆化属性值的最佳方法

python - 为什么在 Python 中列表访问 O(1)?