二叉树层序遍历代码输出正确但报NoneType属性错误求助
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:
- You immediately put
root(which isNone) into the queue withL.put(root). - When you enter the loop, you pull that
Nonenode out of the queue withnode = L.get(). - The line
local.append(node.val)tries to access thevalattribute of aNoneobject—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

