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

二叉树层序遍历代码输出正确但报NoneType属性错误求助

Fixing the AttributeError in Your Binary Tree Level Order Traversal Code

Hey there! Let's break down why you're seeing that AttributeError: 'NoneType' object has no attribute 'val' error, and how to fix it.

The Root Cause

The problem hits when you pass an empty tree (i.e., root is None) to your levelOrder method. Here's the play-by-play of what goes wrong:

  1. You immediately put root (which is None) into the queue with L.put(root).
  2. When you enter the loop, you pull that None node out of the queue with node = L.get().
  3. The line local.append(node.val) tries to access the val attribute of a None object—this is exactly what triggers the error on Line 21.

Your existing code already does a good job of checking if node.left and node.right exist before enqueuing them, so non-empty trees would work fine. The only missing piece is handling the empty tree scenario upfront.

The Fix

All you need to do is add a quick check at the start of the method to handle empty trees. If root is None, just return an empty list right away. Here's the corrected code:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
import queue
class Solution(object):
    def levelOrder(self, root):
        # Handle empty tree first to avoid enqueuing None
        if not root:
            return []
            
        L = queue.Queue()
        local = []
        result = []
        L.put(root)
        counter = 0
        while not L.empty():
            counter = L.qsize()
            local = []
            while counter > 0:
                node = L.get()
                local.append(node.val)
                if node.left:
                    L.put(node.left)
                if node.right:
                    L.put(node.right)
                counter -= 1
            result.append(local)
        return result

Why This Works

By checking if not root first, we skip all queue operations when there's no tree to traverse. For non-empty trees, your original logic runs perfectly because you only enqueue valid (non-None) child nodes—so every node you pull from the queue will have a val attribute to access.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:35:58