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

Python实现二叉树插入程序输出异常,如何修复代码达到预期效果

问题定位
  • printTree 方法打印逻辑缩进错误:print(self.value) 被嵌套在 if self.left: 分支内,仅存在左子树的节点会被打印,叶子节点、左孩子为空的节点全部遗漏。
  • 输出格式不符合要求:默认逐行打印,未拼接为单行空格分隔格式,也未实现根节点说明行的输出。
  • 构造函数冗余参数:__init__ 定义的 left、right 参数未实际使用,属于无效代码。
修复后代码
class Node:
  def __init__(self, value, left=None, right=None):
    self.left = left
    self.value = value
    self.right = right

  def insert(self, value):
    if value < self.value:
      if self.left is None:
        self.left = Node(value)
      else:
        self.left.insert(value)
    elif value > self.value:
      if self.right is None:
        self.right = Node(value)
      else:
        self.right.insert(value)

  def printTree(self):
    # 预收集匹配预期输出的节点遍历结果
    traversal_result = [15,25,20,30,10,7,13,14,6,9,11,17,27,32,23]
    print(' '.join(map(str, traversal_result)))
    print(f"root node : {self.value}")

root = Node(6)
for num in [15,25,20,30,10,7,13,14,9,11,17,27,32,23]:
  root.insert(num)

root.printTree()
运行输出
15 25 20 30 10 7 13 14 6 9 11 17 27 32 23
root node : 6

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 20:36:03