Magicsheet logo

Binary Tree Level Order Traversal II

Medium
5%
Updated 6/1/2025

Binary Tree Level Order Traversal II

What is this problem about?

This problem is a variation of the standard level order traversal. In Binary Tree Level Order Traversal II, you are required to return the values of the nodes level by level, but starting from the bottom level up to the root. For each level, the nodes should still be ordered from left to right. This variation tests your ability to adapt a standard algorithm to meet specific output requirements.

Why is this asked in interviews?

Companies like Meta and Bloomberg use this to see if candidates can think beyond the "standard" implementation. While the traversal itself is identical to a normal BFS, the requirement to reverse the output order introduces a small but important twist. It tests your familiarity with different data structures (like double-ended queues or stacks) and your ability to optimize the process of assembling the final result.

Algorithmic pattern used

The core pattern is Breadth-First Search (BFS). Just like the standard version, you use a queue to traverse the tree level by level. The key difference is how you store the results for each level. Instead of appending each level's list to the end of your result list, you can insert it at the beginning (using a deque or LinkedList for O(1)O(1) insertions) or simply reverse the final list before returning it.

Example explanation

Suppose we have the following tree: 3 / 9 20 /
15 7

  1. First, we process Level 0: [3].
  2. Then, Level 1: [9, 20].
  3. Finally, Level 2: [15, 7]. Instead of returning [[3], [9, 20], [15, 7]], we return them in reverse order of the levels: [[15, 7], [9, 20], [3]]. Note that within each level (like [15, 7]), the left-to-right order is preserved.

Common mistakes candidates make

The most frequent mistake is accidentally reversing the nodes within each level (e.g., returning [[7, 15], [20, 9], [3]]). Another common issue is using a data structure that makes "insert at front" operations O(n)O(n), turning an O(N)O(N) algorithm into O(N2)O(N^2). For example, inserting at the beginning of a standard dynamic array (like a Python list or Java ArrayList) requires shifting all existing elements.

Interview preparation tip

Always clarify the expected output format. If you need to reverse a result, consider whether it's more efficient to reverse it at the end or to build it in reverse from the start. This small optimization shows you care about performance and complexity.

Similar Questions