Binary Tree Level Order Traversal
Medium · Trees
Jump to codeReturn a binary tree’s values grouped by depth, from the root level downward and left to right within each level.
Examples
Example 1
root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Example 2
root = [1]
Output: [[1]]
Constraints
- 0 <= The number of nodes in the tree <= 1000
- -1000 <= Node.val <= 1000
Function contract
Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.
Need a hint?
Snapshot the queue size before processing a level.
Asked in real interviews
Candidates reported versions of Binary Tree Level Order Traversal from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Use a queue seeded with the root if present. At each step, remove exactly the number of nodes currently queued, collect their values, and enqueue their left then right children. Append the collected level and repeat. An empty tree yields an empty list.
Complexity
O(n) time and O(w) auxiliary space for maximum width w, excluding output.
Python reference solution
from collections import deque
def levelOrder(root):
if root is None:
return []
queue = deque([root])
levels = []
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
levels.append(level)
return levels
JavaScript solution
function levelOrder(root) {
if (!root) return [];
let queue = [root];
const levels = [];
while (queue.length) {
const next = [], level = [];
for (const node of queue) {
level.push(node.val);
if (node.left) next.push(node.left);
if (node.right) next.push(node.right);
}
levels.push(level);
queue = next;
}
return levels;
}
Java solution
import java.util.*;
class Solution {
public int[][] levelOrder(TreeNode root) {
if (root == null) return new int[0][];
Queue<TreeNode> queue = new ArrayDeque<>();
List<int[]> levels = new ArrayList<>();
queue.add(root);
while (!queue.isEmpty()) {
int[] level = new int[queue.size()];
for (int i = 0; i < level.length; i++) {
TreeNode node = queue.remove();
level[i] = node.val;
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
levels.add(level);
}
return levels.toArray(new int[0][]);
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (!root) return {};
queue<TreeNode*> pending;
pending.push(root);
vector<vector<int>> levels;
while (!pending.empty()) {
int size = pending.size();
vector<int> level;
for (int i = 0; i < size; i++) {
TreeNode* node = pending.front(); pending.pop();
level.push_back(node->val);
if (node->left) pending.push(node->left);
if (node->right) pending.push(node->right);
}
levels.push_back(move(level));
}
return levels;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
3,
9,
20,
null,
null,
15,
7
]
][
[
3
],
[
9,
20
],
[
15,
7
]
][
[
1
]
][
[
1
]
][ [] ]
[]
[
[
1,
null,
2,
3
]
][
[
1
],
[
2
],
[
3
]
][
[
1,
2,
3,
4,
null,
null,
5
]
][
[
1
],
[
2,
3
],
[
4,
5
]
]Drafts are saved per language in this browser when storage is available.