MEDIUM NC#53 Blind #64 Trees / BFS
102. Binary Tree Level Order Traversal
๐ Problem
Given the root of a binary tree, return the level order traversal of its nodes' values (i.e., from left to right, level by level).
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขLevel-order traversal
- โขQueue discipline
- โขShortest-step interpretation
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply BFS reasoning pattern
๐ก Approach
- โ Use BFS (queue) for level order traversal
- โ Process all nodes at current level before moving to next
- โ Collect each level's values separately
- โ Time: O(n), Space: O(w) where w is max width
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse BFS (queue) for level order traversal
- โขProcess all nodes at current level before moving to next
- โขCollect each level's values separately
Common Pitfalls
- โขTime: O(n), Space: O(w) where w is max width
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
levelOrder(buildTree([3,9,20,null,null,15,7])); Expected:
[[3], [9,20], [15,7]] Test Case 2
Not run Input:
levelOrder(buildTree([1])); Expected:
[[1]] Test Case 3
Not run Input:
levelOrder(buildTree([])); Expected:
[] ๐ Code Editor
๐ค Output