Binary Tree Level Order Traversal
LeetCode 102 · Medium · solution, intuition & step-by-step walkthrough
BFS with a level marker.
This is how I solved Binary Tree Level Order Traversal (LeetCode 102), a medium problem from the BFS / Level Order pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Breadth-first search with a queue visits nodes level by level. A marker ('\n') in the queue tells you where one level ends and the next begins.
Approach
- 1
Queue starts with root and a marker.
- 2
Pop: marker → re-append it and start a new level list.
- 3
Node → add its value and enqueue its children.
- 4
Stop when only the marker is left.
How I solved it
BFS with markerPythonO(n) time · O(n) space
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if root is None:
return []
queue=deque([root,"\n"])
res=[[]]
while len(queue)>1:
node= queue.popleft()
if node is None:
continue
if node is "\n":
queue.append(node)
res.append([])
continue
res[-1].append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return resBinary Tree Level Order Traversal — FAQ
What is the intuition behind Binary Tree Level Order Traversal?
Breadth-first search with a queue visits nodes level by level. A marker ('\n') in the queue tells you where one level ends and the next begins.
How do you solve Binary Tree Level Order Traversal (LeetCode 102)?
1. Queue starts with root and a marker. 2. Pop: marker → re-append it and start a new level list. 3. Node → add its value and enqueue its children. 4. Stop when only the marker is left.
What is the time and space complexity of Binary Tree Level Order Traversal?
Time: O(n). Space: O(n). (Accepted approach: BFS with marker.)
What are common mistakes in Binary Tree Level Order Traversal?
`node is "\n"` relies on string interning; == is the safe comparison.