Binary Tree Level Order Traversal II (LeetCode 107): Solution and Explanation
Given the root of a binary tree, return its values grouped by level, with the deepest level first and the root last. Each level lists its values from left to right. The tree has up to 2000 nodes and may be empty.
Intuition
The top-down version is the classic breadth-first search: a queue that, at the start of every round, holds exactly one level of the tree. Pop that many nodes, collect their values, and queue their children for the next round.
Bottom-up does not change the order in which you discover levels. You still reach the root first, because you can only get to a node through its parent. What changes is only the order of the finished levels in the answer.
So keep the BFS exactly as it is and change where each level goes. If every finished level is inserted at the front of the result, the first level read (the root) ends up at the back and the last level read (the deepest) ends up at the front.
A deque makes the front insert O(1). Appending normally and reversing once at the end works just as well and is the same total cost.
Approach: BFS by level with front insertion
- If the root is null, return an empty list.
- Create a deque
resfor the answer and a queueqholding the root. - While
qis not empty, take its current size: that many nodes form one level. - Pop each of them, append its value to
level, and queue its left and right children if they exist. - Insert the finished
levelat the front ofres. - When the queue is empty, return
resas a list.
Step-by-step example
root = [3,9,20,null,null,15,7]
- The queue starts as [3]. Round 1 pops 3, queues 9 and 20. Level [3] goes to the front of
res: [[3]]. - Round 2 sees two nodes. Pop 9 (a leaf), then pop 20 and queue 15 and 7. Level [9,20] goes to the front: [[9,20],[3]].
- Round 3 sees two nodes, 15 and 7, both leaves. Level [15,7] goes to the front: [[15,7],[9,20],[3]].
- The queue is empty, so return [[15,7],[9,20],[3]].
Code: Python, Java, C++
1class Solution:
2 def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
3 res = deque()
4 if not root:
5 return []
6 q = deque([root])
7 while q:
8 level = []
9 for _ in range(len(q)):
10 node = q.popleft()
11 level.append(node.val)
12 if node.left:
13 q.append(node.left)
14 if node.right:
15 q.append(node.right)
16 res.appendleft(level)
17 return list(res)1class Solution {
2 public List<List<Integer>> levelOrderBottom(TreeNode root) {
3 LinkedList<List<Integer>> res = new LinkedList<>();
4 if (root == null) return res;
5 Queue<TreeNode> q = new ArrayDeque<>();
6 q.offer(root);
7 while (!q.isEmpty()) {
8 List<Integer> level = new ArrayList<>();
9 for (int i = q.size(); i > 0; i--) {
10 TreeNode node = q.poll();
11 level.add(node.val);
12 if (node.left != null) q.offer(node.left);
13 if (node.right != null) q.offer(node.right);
14 }
15 res.addFirst(level);
16 }
17 return res;
18 }
19}1class Solution {
2public:
3 vector<vector<int>> levelOrderBottom(TreeNode* root) {
4 deque<vector<int>> res;
5 if (!root) return {};
6 queue<TreeNode*> q;
7 q.push(root);
8 while (!q.empty()) {
9 vector<int> level;
10 for (int i = q.size(); i > 0; i--) {
11 TreeNode* node = q.front();
12 q.pop();
13 level.push_back(node->val);
14 if (node->left) q.push(node->left);
15 if (node->right) q.push(node->right);
16 }
17 res.push_front(level);
18 }
19 return vector<vector<int>>(res.begin(), res.end());
20 }
21};Time and space complexity
O(n)
Every node enters and leaves the queue once, and each front insertion into the deque is O(1).
O(n)
The answer holds all n values. The queue holds at most one level, which can be about n / 2 nodes in a complete tree.
Other approaches
BFS then reverse (time O(n), space O(n))
Run the usual top-down level order traversal, appending each level to a list, and reverse the list once at the end. Same cost, and some people find it easier to read.
DFS with a depth index (time O(n), space O(n))
Recurse with the current depth and append each value to levels[depth], creating the list the first time a depth is reached. Visiting left before right keeps each level in left-to-right order. Reverse the list of levels at the end.
Common mistakes
- Using
list.insert(0, level)on a Python list. It shifts every earlier level each time, which is quadratic in the number of levels for a tall, skewed tree. - Reading
len(q)inside the loop condition instead of once before popping. The queue grows while you pop, so the level boundary gets lost. - Reversing the values inside each level. Only the order of the levels flips; each level still reads left to right.
- Forgetting the empty tree. Putting a null root into the queue leads to a null dereference or a level containing null.
Frequently asked questions
Can I traverse from the bottom of the tree directly?
Not without extra work. Nodes only point to their children, so you can only reach deep nodes by going through shallow ones. It is simpler to read levels top-down and reverse their order.
Is inserting at the front better than reversing at the end?
With a deque, both are O(n) in total. Front insertion builds the answer in its final order as you go, which can be easier to reason about. Reversing at the end is one extra line.
How does this differ from Binary Tree Level Order Traversal?
The traversal is identical. Only the position where each finished level is stored changes, so the levels come out deepest first instead of root first.