Binary Tree Level Order Traversal
Medium
Topics
Given the root of a binary tree, return its level-order traversal — a list of levels, each a list of node values from left to right. On this judge levels are shown separated by |.
Example 1
The answer groups nodes by level, one inner list each (the three shades mark the first three levels). A plain queue visits nodes in the right order but loses the grouping; draining exactly the current queue length before moving on restores it.
Tree given in level-order (breadth-first);
null marks a missing child.Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]]
Example 2
empty tree
Input: root = [] Output: []
Constraints
- 0 <= number of nodes <= 2000
- -1000 <= Node.val <= 1000
Editorial — intuition, approach, complexity and pitfalls
Intuition
A breadth-first traversal naturally visits the tree level by level. Process the queue one full level at a time by capturing its size before the inner loop.
Approach
- Push the root; if null, return empty.
- While the queue is non-empty, record its current size — that is one level.
- Pop exactly that many nodes into the current level list, enqueueing their children.
Dry Run
tree 3 9 20 null null 15 7
3
/ \
9 20
/ \
15 7
The queue is shared across levels, so the level boundary has to be captured
before any children are added:
snapshot len(q)=1 pop [3] enqueue 9, 20 queue [9, 20]
snapshot len(q)=2 pop [9, 20] enqueue 15, 7 queue [15, 7]
snapshot len(q)=2 pop [15, 7] enqueue nothing queue []
answer [3] | [9, 20] | [15, 7]
That snapshot is the only interesting line in the algorithm. Read the length
live -- `while q` on the inner loop -- and the children appended during a level
get consumed by the same level, which collapses the whole tree into one list:
[[3, 9, 20, 15, 7]]. The levels do not just shift, they dissolve.
Note that nulls are never enqueued; the `if node.left` guards keep them out. That
is why level 3 contains 15 and 7 rather than four entries with two holes -- the
output has no notion of position within a level, only membership.Complexity
- Time — O(n): each node is enqueued and dequeued once.
- Space — O(n): the queue can hold a full level.
Common Pitfalls
- Snapshot the queue length before the inner loop, since you keep adding children to the same queue.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def levelOrder(self, root):
if not root: return []
from collections import deque
res=[]; q=deque([root])
while q:
level=[]
for _ in range(len(q)):
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 resimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res=new ArrayList<>();
if(root==null)return res;
Queue<TreeNode> q=new LinkedList<>();
q.add(root);
while(!q.isEmpty()) {
int sz=q.size();
List<Integer> level=new ArrayList<>();
for(int i=0;i<sz;i++) {
TreeNode n=q.poll();
level.add(n.val);
if(n.left!=null)q.add(n.left);
if(n.right!=null)q.add(n.right);
}
res.add(level);
}
return res;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
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()) {
int sz=q.size();
vector<int> level;
for(int i=0;i<sz;i++) {
TreeNode* n=q.front();
q.pop();
level.push_back(n->val);
if(n->left)q.push(n->left);
if(n->right)q.push(n->right);
}
res.push_back(level);
}
return res;
}
};/** Tree node shape: { val, left, right } */ /**
* @param {TreeNode} root
* @return {number[][]}
*/ var levelOrder = function(root) {
if(!root)return [];
const res=[];
let q=[root];
while(q.length) {
const level=[],nq=[];
for(const node of q) {
level.push(node.val);
if(node.left)nq.push(node.left);
if(node.right)nq.push(node.right);
}
res.push(level);
q=nq;
}
return res;
};