Knowledge Guide
HomeDSATrees

easy Reverse Level Order Traversal

Problem Statement

Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., the lowest level comes first in left to right order.)

Examples

Example 1

Example 2

Example 3

Constraints:

Try it yourself

Try solving this question here:

✅ Solution Reverse Level Order Traversal

Problem Statement

Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., the lowest level comes first in left to right order.)

Examples

Example 1

  • Input: root = [1, 2, 3, 4, 5, 6, 7]
Image
Image
  • Expected Output: [[4, 5, 6, 7], [2, 3], [1]]
  • Justification:
    • The third level has 4, 5, 6, and 7 nodes.
    • The second level has 2 and 3 nodes.
    • The first level has a single node with the value 1.

Example 2

  • Input: root = [12, 7, 1, null, 9, 10, 5]
Image
Image
  • Expected Output: [[9, 10, 5], [7, 1], [12]]
  • Justification:
    • The third level has 9, 10, and 5 nodes.
    • The second level has 7 and 1 nodes.
    • The first level has a single node with the value 12.

Example 3

  • Input: root = [6,5,2,null,null,1,6,3,56,3]
Image
Image
  • Expected Output: [[3,56,3],[1,6],[5,2],[6]]
  • Justification:
    • The fourth level has 3, 56, and 3 nodes.
    • The third level has 1, and 6 nodes.
    • The second level has 5 and 2 nodes.
    • The first level has a single node with the value 6.

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

Solution

To solve the reverse level order traversal problem, we will perform a breadth-first search (BFS) using a queue. The idea is to traverse the tree level by level from top to bottom but store each level's result in reverse order. At each level, we process all nodes, add their values to the current level list, and then enqueue their left and right children. Instead of appending the level at the end of the result, we insert it at the beginning, ensuring that when we finish, the result is in reverse level order.

Step-by-Step Algorithm

  1. Initialization:

    • If the root is null, return an empty list because there is no tree to traverse.
    • Initialize a queue to help with the BFS traversal. The queue will store nodes that need to be processed.
    • Initialize an empty list result to store the final reversed level order traversal.
  2. Start BFS Traversal:

    • Add the root node to the queue. This represents the starting point of the level order traversal.
  3. Process Nodes Level by Level:

    • While the queue is not empty, do the following:
      • Find out how many nodes are on the current level by checking the size of the queue (levelSize = queue.size()).
      • Initialize an empty list currentLevel to store the values of the nodes at this level.
  4. Process Each Node in the Current Level:

    • For each node at the current level, repeat the following steps:
      • Dequeue the front node of the queue.
      • Add the value of the node to the currentLevel list.
      • If the dequeued node has a left child, enqueue the left child.
      • If the dequeued node has a right child, enqueue the right child.
  5. Add the Current Level to the Result:

    • Once all nodes at the current level have been processed, add the currentLevel list to the front of the result list. This ensures that the levels are inserted in reverse order.
  6. Repeat:

    • Repeat the process until all nodes have been processed and the queue is empty.
  7. Return the Final Result:

    • After processing all the levels, return the result list, which contains the node values in reverse level order.

Algorithm Walkthrough

Input: root = [12, 7, 1, null, 9, 10, 5]

Image
Image
  1. Initialization:

    • Root: 12
    • Initialize queue = [12]
    • Initialize result = []
  2. First Level:

    • levelSize = 1 (only one node at this level: 12)
    • Initialize currentLevel = []
    • Dequeue 12, add its value to currentLevel: currentLevel = [12]
    • Enqueue the left child (7) and right child (1): queue = [7, 1]
    • Insert currentLevel at the beginning of result: result = [[12]]
  3. Second Level:

    • levelSize = 2 (two nodes at this level: 7 and 1)
    • Initialize currentLevel = []
    • Dequeue 7, add its value to currentLevel: currentLevel = [7]
    • Enqueue the right child (9), no left child: queue = [1, 9]
    • Dequeue 1, add its value to currentLevel: currentLevel = [7, 1]
    • Enqueue the left child (10) and right child (5): queue = [9, 10, 5]
    • Insert currentLevel at the beginning of result: result = [[7, 1], [12]]
  4. Third Level:

    • levelSize = 3 (three nodes at this level: 9, 10, and 5)
    • Initialize currentLevel = []
    • Dequeue 9, add its value to currentLevel: currentLevel = [9]
    • Dequeue 10, add its value to currentLevel: currentLevel = [9, 10]
    • Dequeue 5, add its value to currentLevel: currentLevel = [9, 10, 5]
    • No more children to enqueue: queue = []
    • Insert currentLevel at the beginning of result: result = [[9, 10, 5], [7, 1], [12]]
  5. Final Result:

    • The queue is now empty, so we return the result.
    • The final reverse level order traversal is [[9, 10, 5], [7, 1], [12]].

Final Output:

  • The reverse level order traversal for the tree [12, 7, 1, null, 9, 10, 5] is [[9, 10, 5], [7, 1], [12]].

Code

java
import java.util.*;

// class TreeNode {
//   int val;
//   TreeNode left;
//   TreeNode right;

//   TreeNode(int x) {
//     val = x;
//   }
// };

class Solution {

  public List<List<Integer>> traverse(TreeNode root) {
    List<List<Integer>> result = new LinkedList<List<Integer>>();
    if (root == null) return result;

    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while (!queue.isEmpty()) {
      int levelSize = queue.size();
      List<Integer> currentLevel = new ArrayList<>(levelSize);
      for (int i = 0; i < levelSize; i++) {
        TreeNode currentNode = queue.poll();
        // add the node to the current level
        currentLevel.add(currentNode.val);
        // insert the children of current node to the queue
        if (currentNode.left != null) queue.offer(currentNode.left);
        if (currentNode.right != null) queue.offer(currentNode.right);
      }
      // append the current level at the beginning
      result.add(0, currentLevel);
    }

    return result;
  }

  public static void main(String[] args) {
    Solution sol = new Solution();
    TreeNode root = new TreeNode(12);
    root.left = new TreeNode(7);
    root.right = new TreeNode(1);
    root.left.left = new TreeNode(9);
    root.right.left = new TreeNode(10);
    root.right.right = new TreeNode(5);
    List<List<Integer>> result = sol.traverse(root);
    System.out.println("Reverse level order traversal: " + result);
  }
}

Time Complexity

The time complexity of the above algorithm is , where ‘N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once.

Space Complexity

The space complexity of the above algorithm will be as we need to return a list containing the level order traversal. We will also need space for the queue. Since we can have a maximum of N/2 nodes at any level (this could happen only at the lowest level), therefore we will need space to store them in the queue.

🤖 Don't fully get this? Learn it with Claude

Stuck on Reverse Level Order Traversal? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Reverse Level Order Traversal** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Reverse Level Order Traversal** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Reverse Level Order Traversal**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Reverse Level Order Traversal**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes