【问题标题】:how to print a binary search tree in python?如何在python中打印二叉搜索树?
【发布时间】:2020-06-16 10:40:19
【问题描述】:

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

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)

【问题讨论】:

  • 互联网上有很多实现...你问这个问题之前有没有研究过?如果您尝试过,但没有成功,请询问有关您的实现、共享代码以及您遇到的问题的问题。
  • 你可以使用树遍历算法inoredr(), preorder(), postorder() and levelorder() 任何一种都可以
  • 您是否也意识到您的实现不能超过 3 个节点?它将替换节点...
  • 这可能对towardsdatascience.com/…有帮助
  • 非常感谢您的友好回复先生!!

标签: python data-structures


【解决方案1】:

你的实现有一些问题:

  • 这棵树只能有 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))

【讨论】:

    【解决方案2】:

    这里是二叉搜索树的简单实现。此外,我建议您不要将== 运算符与None 一起使用,而不要使用is,此处为why should I avoid == None

    class Node: 
        def __init__(self,key): 
            self.left = None
            self.right = None
            self.value = key 
    
    
    def insert(root,node): 
        if root is None: 
            root = node 
        else: 
            if root.value < node.value: 
                if root.right is None: 
                    root.right = node 
                else: 
                    insert(root.right, node) 
            else: 
                if root.left is None: 
                    root.left = node 
                else: 
                    insert(root.left, node) 
    
    
    def left_right(root): 
        if root: 
            left_right(root.left) 
            print(root.value)  # that shows your tree
            left_right(root.right) 
            
    
    tree = Node(20) 
    insert(tree,Node(30)) 
    insert(tree,Node(10)) 
    insert(tree,Node(40)) 
    insert(tree,Node(90))
    
    left_right(tree) 
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多