Binary Tree Level Order Traversal II - Problem

Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. This means traversing from left to right, level by level from leaf to root.

In other words, collect all nodes at each level, but return the levels in reverse order - starting from the deepest level and ending at the root level.

For example, if a tree has 3 levels, return the nodes in order: Level 3 → Level 2 → Level 1

Input & Output

Example 1 — Basic Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]
💡 Note: Level order traversal gives [[3],[9,20],[15,7]]. Reversing gives [[15,7],[9,20],[3]] for bottom-up order.
Example 2 — Single Node
$ Input: root = [1]
Output: [[1]]
💡 Note: Tree has only one level with one node. Result is [[1]].
Example 3 — Empty Tree
$ Input: root = []
Output: []
💡 Note: Empty tree returns empty result.

Constraints

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

Visualization

Tap to expand
Binary Tree Level Order Traversal II INPUT Binary Tree Structure 3 9 20 15 7 Level 0 Level 1 Level 2 Input Array: [3, 9, 20, null, null, 15, 7] null = no child node ALGORITHM (BFS) 1 Initialize Queue Start with root node Q: [3] 2 BFS Level by Level Process each level, add children L0: process [3] --> add 9,20 L1: process [9,20] --> add 15,7 L2: process [15,7] --> no children Result: [[3], [9,20], [15,7]] 3 Collect Levels Store nodes at each level 4 Reverse Order Return levels bottom-up reverse() FINAL RESULT Bottom-up traversal order Output[0] - Level 2: 15 7 Output[1] - Level 1: 9 20 Output[2] - Level 0: 3 Final Output: [[15,7],[9,20],[3]] OK - Complete! Bottom-up order achieved Key Insight: BFS naturally traverses level by level (top to bottom). To get bottom-up order, simply reverse the result array at the end. Alternatively, insert each level at the beginning of the result list during traversal. Time Complexity: O(n) | Space Complexity: O(n) where n = number of nodes TutorialsPoint - Binary Tree Level Order Traversal II | BFS Approach
Asked in
Amazon 42 Microsoft 35 Facebook 28 Apple 22
98.8K Views
Medium Frequency
~15 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen