50. Binary Tree Level Order Traversal
Return the node values level by level, from left to right.
Example 1
Input:
root = [3,9,20,null,null,15,7]Output:
[[3],[9,20],[15,7]]Example 2
Input:
root = [1]Output:
[[1]]Hint 1
Breadth-first search with a queue.
Hint 2
Process the queue in batches of its current size: one batch = one level.
Approach 1: BFS with level batches ✅
Queue + loop over the current queue size.
⏱ Time O(n)💾 Space O(w)
Reference solution for BFS with level batches (time O(n), space O(w)). Each solution passes every test in all four languages.
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
res, q = [], deque([root])
while q:
level = []
for _ in range(len(q)): # exactly the nodes of this level
node = q.popleft()
level.append(node.val)
if node.left: q.append(node.left)
if node.right: q.append(node.right)
res.append(level)
return resclass Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
while (!q.isEmpty()) {
List<Integer> level = new ArrayList<>();
for (int k = q.size(); k > 0; k--) {
TreeNode node = q.poll();
level.add(node.val);
if (node.left != null) q.add(node.left);
if (node.right != null) q.add(node.right);
}
res.add(level);
}
return res;
}
}class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if (!root) return res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
vector<int> level;
for (int k = q.size(); k > 0; k--) {
TreeNode* node = q.front(); q.pop();
level.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
res.push_back(level);
}
return res;
}
};function levelOrder(root) {
if (!root) return [];
const res = [];
let level = [root];
while (level.length) {
res.push(level.map(n => n.val));
const next = [];
for (const n of level) { if (n.left) next.push(n.left); if (n.right) next.push(n.right); }
level = next;
}
return res;
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
Watch the core idea of this problem step by step. Change the input and press Visualize.
Explained in the lesson Binary Trees & BSTs.
Run your code to see results here.