Problem
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
Examples
Example 1:
graph TD; 3 --> 9 & 20 20 --> 15 & 7;
|
|
Example 2:
|
|
graph TD; 7 --> 1 & 9 1 --> 0 & 3 9 --> 8 & 10 3 --> 2 & 5 5 --> 4 & 6
Variants
There are multiple variants possible for Level Order Traversal.
- Binary Tree Level Order Traversal - Level by Level
- Binary Tree Traversal - Zigzag Level Order Traversal
- Binary Tree Traversal - Level Order Bottom up
Solution
Method 1 - Iterative BFS Using Queue 🏆
Here is the approach:
- Start with an empty queue.
- Add one node, the root of the tree, to the queue.
- Loop until the queue is empty:
- Dequeue a node.
- Print its value.
- Add its left and right children if they exist.
Pseudocode
|
|
Hence the running time would be O(N).
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
|
|
|
|
Method 2 - Using 2 Stacks
Here is the logic:
|
|
Complexity
The level order traversal algorithm using two stacks exhibits a time complexity dependent on the tree’s height, particularly in skewed cases.
- Nested Loops: The algorithm employs two nested loops. The outer loop iterates for
O(H)
times, whereH
represents the tree’s height. This loop ensures each level is visited. - Inner Loop and Level Iteration: Within each outer loop iteration, an inner loop processes the nodes in the current level. This inner loop’s execution time scales with the number of nodes in that level. In a balanced tree, the number of nodes at each level roughly doubles compared to the previous level, leading to an exponential growth of
O(2^K)
for the inner loop, whereK
represents the current level.
Combined Complexity:
Combining the outer and inner loops’ contributions, the initial expression for runtime becomes O(H) * O(2^K) + O(2^K)
. However, the constant term O(2^K)
within the first summation can be ignored as it grows slower than the exponential term. Simplifying further, we get O(2^K) * (O(H) + 1)
, which essentially translates to O(H) * O(2^K)
.