You need to enable JavaScript to run this app. Python实现树数据结构时报AttributeError,求错误原因及修复方法
优惠活动
大模型
产品
解决方案
定价
更多

Python实现树数据结构时报AttributeError,求错误原因及修复方法

错误原因拆解
  • 属性归属混淆:data是Node类的成员属性,但你直接访问Tree实例的data,Tree类本身没有定义这个属性,自然触发AttributeError。另外插入逻辑中你给Node的leftChild/rightChild赋值的是Tree(val),而Node的子节点本该是Node实例,两种类的实例混存导致逻辑完全混乱。
  • 遍历未做空判断:你写的inorder方法里,没有判断leftChild/rightChild是否为None就直接调用inorder()方法,叶子节点的子节点默认是None,没有任何属性方法,自然触发NoneType无对应属性的报错。另外你在Tree类里同时存head和root两个完全相同的属性,属于冗余设计,没有必要。
  • 主函数逻辑错误:你先让用户输入根节点值n,但创建Tree实例时写死了Tree(5),完全没用上用户输入的内容。
修正后的完整代码
class Node:
    def __init__(self,val):
        self.data = val
        self.leftChild = None
        self.rightChild = None

class Tree:
    def __init__(self,val):
        self.root = Node(val) # 仅保留root作为根节点属性
    
    # 插入逻辑修正:子节点存储Node实例,递归操作Node对象
    def insert(self,val):
        def insert_recursive(node, val):
            if val > node.data:
                if not node.rightChild:
                    node.rightChild = Node(val)
                    print("{} inserted in Right Tree".format(val))
                else:
                    insert_recursive(node.rightChild, val)
            elif val < node.data:
                if not node.leftChild:
                    node.leftChild = Node(val)
                    print("{} inserted in Left Tree".format(val))
                else:
                    insert_recursive(node.leftChild, val)
        insert_recursive(self.root, val)
    
    # 中序遍历修正:先判断节点非空再执行递归
    def inorder(self):
        def inorder_recursive(node):
            if node:
                inorder_recursive(node.leftChild)
                print(node.data)
                inorder_recursive(node.rightChild)
        inorder_recursive(self.root)

if __name__ == "__main__":
    n = int(input("Enter the value for the root node : "))
    a = list(map(int,input("Enter the values to be inserted in the tree : ").split()))
    root = Tree(n) # 调用用户输入的根节点值
    for i in a:
        root.insert(i)
    # 访问节点属性需要先通过Tree的root属性拿到Node实例
    print("根节点值:", root.root.data)
    if root.root.leftChild:
        print("左子节点值:", root.root.leftChild.data)
    if root.root.rightChild:
        print("右子节点值:", root.root.rightChild.data)
    print("中序遍历结果:")
    root.inorder()
效果验证

输入示例:

Enter the value for the root node : 5
Enter the values to be inserted in the tree : 1 6

输出结果:

1 inserted in Left Tree
6 inserted in Right Tree
根节点值: 5
左子节点值: 1
右子节点值: 6
中序遍历结果:
1
5
6

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 17:12:04