AAlgoLoopSpaced repetition for LeetCode
MEDIUMBFS / DFSLeetCode ↗

Binary Tree Level Order Traversal II

The key idea

Do an ordinary top-down breadth-first sweep, collecting one list per level. The only twist over normal level-order traversal is that the answer wants the levels from the bottom up, so reverse the list of levels (or prepend each new level to the front) at the end.

Problem

Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values — that is, group the node values by depth, then list the groups from the leaf level up to the root, with each level read left to right.

Every node on the same depth belongs to the same level. The last group in the answer is the root's own level [root.val]; the first group is the deepest level of the tree. If the tree is empty (root is null), return an empty list.

Constraints

Examples

Input: root = [3,9,20,null,null,15,7] Output: [[15,7],[9,20],[3]]
Input: root = [1] Output: [[1]]
Input: root = [] Output: []

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems