Binary Tree Level Order Traversal — Python Solution
Level Order Traversal is one of the fundamental tree traversal techniques where we visit every node of a binary tree level by level, starting from the root and moving left-to-right within each level. It’s widely used in breadth-first search (BFS) patterns and is a staple in algorithm interviews. :contentReference[oaicite:0]{index=0}
๐ก What is Level Order Traversal?
Given the root of a binary tree, the goal is to return a nested list where each sublist represents all node values at that specific level of the tree.
For example, for the binary tree:
Input: root = [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
The expected traversal output is:
[
[3],
[9,20],
[15,7]
]
๐ Idea Behind the Approach
To traverse level by level, we use a queue. A queue processes nodes in FIFO order, enabling breadth-first traversal. At each step:
- We track the number of nodes in the current level.
- We iterate over all of them, pushing their non-null children to the queue for the next level.
- We collect values level by level into the result list.
This ensures we never mix nodes from different depths. :contentReference[oaicite:1]{index=1}
๐ง Python Implementation
# 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
from collections import deque
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
result = []
q = deque([root])
while q:
current_level = []
for _ in range(len(q)):
root = q.popleft()
if root:
current_level.append(root.val)
q.append(root.left)
q.append(root.right)
if current_level:
result.append(current_level)
return result
๐ This solution handles empty trees gracefully and guarantees that only non-null nodes are added to the result. Each level is collected independently and appended only if non-empty.
๐งช Time and Space Complexity
- Time Complexity:
O(n)— We visit each node exactly once. - Space Complexity:
O(n)— In the worst case, the queue might hold all nodes on the widest level of the tree.
๐ Visual Intuition
Imagine a wave spreading out level by level: you process the current tier of nodes, then enqueue all children for the next tier — just like a BFS ripple spreading outward from the root. :contentReference[oaicite:2]{index=2}
๐ Final Thoughts
Level Order Traversal is a classic BFS application. With this pattern, you can build many variations like zigzag traversal, level averages, right-side view, and more.
GitHub Solution - Click here
Happy coding! ๐
Comments
Post a Comment
Share your views on this blog๐๐