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

自定义Tree类调用print_tree方法无法正常打印树结构是什么原因

代码无法正常运行的原因

你的代码存在三类明显的语法和逻辑错误,直接导致无法正常打印树结构:

  • 类方法缩进错误:add_children、level_func两个方法被定义在了treeNode.__init__的缩进块内部,属于构造函数的局部函数,类实例无法正常调用这两个方法,运行时会直接报属性不存在错误。
  • nextSibling属性赋值错误:
    1. 类型不匹配:当前代码把节点的data值赋值给nextSibling,但nextSibling需要存储下一个兄弟节点的实例对象,后续遍历用非节点对象调用方法会直接崩溃。
    2. 关联逻辑错误:当前所有子节点的nextSibling都指向自身的data,没有实现兄弟节点的链式关联,完全无法支撑你设计的遍历策略。
  • 遍历逻辑错误:
    1. 跳转逻辑写反:print_tree中无子节点后的循环判断条件逻辑完全不符合你的设计规则,会导致遍历提前终止或进入死循环。
    2. 缺少边界判断:根节点无子节点时直接取self.root.children[0]会触发索引越界错误。
修正后可正常运行的代码
class treeNode:
    def __init__(self, data):
        self.data = data
        self.children = []
        self.parent = None
        self.nextSibling = None
        self.level = 0

    def add_children(self, *child):
        for i in child:
            i.parent = self
            # 前一个子节点的nextSibling指向当前新增的子节点
            if len(self.children) > 0:
                self.children[-1].nextSibling = i
            self.children.append(i)

    def level_func(self):
        itr = self
        count = 0
        while itr:
            count += 1
            itr = itr.parent
        self.level = count - 1

class Tree:
    def __init__(self, root: treeNode):
        self.root = root

    def print_tree(self):
        self.root.level_func()
        print(" " * (3 * self.root.level), self.root.data)
        # 根节点无子节点直接返回
        if not self.root.children:
            return
        kid = self.root.children[0]
        # 遍历终止条件:节点为None即遍历完成
        while kid is not None:
            kid.level_func()
            print(" " * (3 * kid.level), kid.data)
            if len(kid.children) > 0:
                # 优先访问子节点
                kid = kid.children[0]
            else:
                # 无子节点则找兄弟节点,无兄弟则向上找父节点的兄弟
                while kid is not None and kid.nextSibling is None:
                    kid = kid.parent
                if kid is None:
                    break
                kid = kid.nextSibling

parent = treeNode(1)
child = treeNode(2)
parent.add_children(child, treeNode(3), treeNode(4), treeNode(5))
grand = treeNode(6)
child.add_children(grand, treeNode(7))
tree1 = Tree(parent)
tree1.print_tree()
运行输出
1
    2
       6
       7
    3
    4
    5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:18:02