You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何打印二叉搜索树(BST)及验证构建代码

二叉搜索树(BST)代码修正与打印函数实现

先指出你代码里的关键问题:

  • TreeNode类中右子节点属性名错误:self.right_right 应改为 self.right_child
  • createBST 内的嵌套函数rootDown逻辑混乱:
    • 嵌套函数无需self参数,调用方式也不正确
    • nodes.pop(elem)用法错误,pop()接收索引而非元素值
    • 比较时错误使用self.root.value,应与当前遍历的节点值对比
    • 处理右子节点时错误赋值给self.right_child,需改为当前节点的node.right_child
    • 处理单个元素就return,导致剩余元素无法插入
  • BST的__init__方法未调用createBST,传入的节点列表不会被处理

以下是修正后的完整代码,同时添加了中序遍历打印(BST中序遍历为升序,可验证树的正确性)和层次遍历打印(直观展示树的层级结构):

class TreeNode:
    def __init__(self, val):
        self.value = val
        self.left_child = None
        self.right_child = None  # 修正属性名

class BST:
    def __init__(self, nodes=None):
        self.root = None
        if nodes:
            self.createBST(nodes.copy())  # 复制列表避免修改原数据

    def createBST(self, nodes):
        if not nodes:
            return
        # 初始化根节点
        self.root = TreeNode(nodes.pop(0))
        # 逐个插入剩余节点
        for elem in nodes:
            self._insert_node(self.root, elem)
    
    # 递归插入节点的辅助函数
    def _insert_node(self, current_node, val):
        if val < current_node.value:
            if current_node.left_child is None:
                current_node.left_child = TreeNode(val)
            else:
                self._insert_node(current_node.left_child, val)
        elif val > current_node.value:
            if current_node.right_child is None:
                current_node.right_child = TreeNode(val)
            else:
                self._insert_node(current_node.right_child, val)
        # 若值与当前节点相等,BST默认不存储重复值,此处直接忽略

    # 中序遍历打印(升序输出,验证BST正确性)
    def inorder_print(self, node=None):
        if node is None:
            node = self.root
        if node.left_child:
            self.inorder_print(node.left_child)
        print(node.value, end=' ')
        if node.right_child:
            self.inorder_print(node.right_child)

    # 层次遍历打印(按层输出,直观展示树结构)
    def level_order_print(self):
        if not self.root:
            return
        queue = [self.root]
        while queue:
            level_size = len(queue)
            for _ in range(level_size):
                current = queue.pop(0)
                print(current.value, end=' ')
                if current.left_child:
                    queue.append(current.left_child)
                if current.right_child:
                    queue.append(current.right_child)
            print()  # 每层结束换行

# 测试代码
bst = BST([90,100,75,50,20])
print("中序遍历结果(应为升序):")
bst.inorder_print()
print("\n层次遍历结果:")
bst.level_order_print()

代码说明

  • _insert_node 递归处理节点插入,确保每个元素放到BST的正确位置
  • 中序遍历输出升序序列,是验证BST结构正确的核心依据
  • 层次遍历按层级输出节点,直观展示树的形态,测试用例的输出为:
    90 
    75 100 
    50 
    20 
    

内容的提问来源于stack exchange,提问作者CRTone24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:20:20