Understanding the Problem
We are given a binary tree, and our goal is to perform a reverse level order traversal. That means instead of visiting nodes from top to bottom and left to right (like in standard level order), we visit nodes from the bottom level up, and within each level, from left to right.
This problem tests your understanding of tree traversal techniques, especially level order traversal using a queue, and how to reverse the result using a stack. We'll go through this step-by-step using an example to help build your intuition.
Step-by-Step Solution with Example
Step 1: Understand the Tree Structure
Let's consider the binary tree represented as: [1, 2, 3, 4, 5, null, 6]. Visually, it looks like this:
1
/ 2 3
/ 4 5 6
Step 2: Use a Queue for Level Order Traversal
We start from the root (node 1) and traverse level by level using a queue. We enqueue the right child before the left child so that when we later reverse the result using a stack, the left-to-right order of nodes is preserved in each level.
Step 3: Push Visited Nodes into a Stack
As we process nodes from the queue, we push each visited node into a stack. This stack helps us reverse the traversal order — since the last nodes processed will come first when popping from the stack.
Step 4: Pop from the Stack for Final Result
Once all nodes have been processed in the queue, we pop elements one by one from the stack to build our final result: the reverse level order traversal.
Step 5: Apply the Steps to the Example
Queue processing order: 1 → 3 → 2 → 6 → 5 → 4 (right before left)
Stack content after traversal: [1, 3, 2, 6, 5, 4]
Final result after popping from stack: [4, 5, 6, 2, 3, 1]
Edge Cases
Case 1: Empty Tree
If the tree is empty (i.e., root is null), then there are no nodes to traverse. We simply return an empty list.
Case 2: Single Node Tree
If the tree has only the root node, the reverse level order traversal is just the value of that single node.
Case 3: Left-Skewed or Right-Skewed Tree
Even in skewed trees (where nodes exist only on one side), the algorithm works correctly — the queue processes each level one by one, and the stack ensures reverse order is achieved.
Finally
This iterative approach to reverse level order traversal is efficient and beginner-friendly. Using a queue to simulate level order traversal and a stack to reverse the result gives us full control over the output structure.
It's important to understand why we enqueue right before left — it ensures the final popped order respects left-to-right orientation per level. Mastering this pattern will help you in many other tree-related problems involving bottom-up traversal.