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

Python实现二叉树插入功能时报AttributeError: 'NoneType'无'data'属性

二叉树插入代码报错排查

错误根因

你的代码存在两个逻辑错误,共同触发了本次报错:

  • 循环内的两次if判断是独立执行的:第一次if temp.data > val触发后会把temp赋值为temp.left,此时temp已经可能是None,紧接着的第二个if temp.data < val会直接访问None的data属性,这就是你本次报错的直接触发点。你看到print(temp.data)能正常输出,是因为打印操作在修改temp指针之前执行,修改后的temp异常不会影响前序的打印逻辑。
  • while循环的退出条件是temp is None,循环结束后你依然尝试访问temp.data执行插入逻辑,即使前面的问题修复,这里也会触发同样的AttributeError。

修复方案

调整循环逻辑,在移动指针前先判断子节点是否为空,若为空则直接插入新节点,不为空再移动指针;同时将两次独立if改为if-elif分支,避免修改temp后重复判断:

class Node:
  def __init__(self, val):
    self.data = val
    self.left = None
    self.right = None

class binaryTree:
  def __init__(self):
    self.root = None

  def insert(self, val):
    if self.root is None:
        self.root = Node(val)
        return
    temp = self.root
    while True:
        print(temp.data)
        if temp.data > val:
            # 左子节点为空直接插入,否则移动指针
            if temp.left is None:
                temp.left = Node(val)
                break
            temp = temp.left
        elif temp.data < val:
            # 右子节点为空直接插入,否则移动指针
            if temp.right is None:
                temp.right = Node(val)
                break
            temp = temp.right
        # 可自行补充节点值相等的情况处理逻辑
tree = binaryTree()
tree.insert(50)
tree.insert(30)
tree.insert(20)

修复后的代码可正常执行所有插入操作,不会触发属性错误,生成的二叉树结构符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:48:04