Trees & BST · Pattern 3 of 12
Level order traversal: BFS one level at a time
Put the root in a queue. Each round, read the queue size, pop exactly that many nodes and push their children: those nodes are one level.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Anything "per level" or "level by level"
- Zigzag, reversed or bottom-up level order
- Connect each node to its right neighbour
- A check where the first missing node matters (is the tree complete?)
The template
List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
Deque<TreeNode> q = new ArrayDeque<>();
if (root != null) q.offer(root);
while (!q.isEmpty()) {
int size = q.size(); // the nodes of this level
List<Integer> level = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode node = q.poll();
level.add(node.val);
if (node.left != null) q.offer(node.left);
if (node.right != null) q.offer(node.right);
}
res.add(level);
}
return res;
}
// complete tree: in BFS order, no real node may come after the first null
boolean isCompleteTree(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>(); // LinkedList accepts nulls
q.offer(root);
boolean seenNull = false;
while (!q.isEmpty()) {
TreeNode node = q.poll();
if (node == null) { seenNull = true; continue; }
if (seenNull) return false;
q.offer(node.left);
q.offer(node.right);
}
return true;
} from collections import deque
def level_order(root):
res = []
q = deque([root] if root else [])
while q:
level = []
for _ in range(len(q)): # 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 res
# complete tree: in BFS order, no real node may come after the first null
def is_complete_tree(root):
q, seen_null = deque([root]), False
while q:
node = q.popleft()
if not node:
seen_null = True
continue
if seen_null:
return False
q.append(node.left)
q.append(node.right)
return True vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> q;
if (root) q.push(root);
while (!q.empty()) {
int size = q.size(); // the nodes of this level
vector<int> level;
for (int i = 0; i < size; i++) {
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;
}
// complete tree: in BFS order, no real node may come after the first null
bool isCompleteTree(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
bool seenNull = false;
while (!q.empty()) {
TreeNode* node = q.front(); q.pop();
if (!node) { seenNull = true; continue; }
if (seenNull) return false;
q.push(node->left);
q.push(node->right);
}
return true;
} function levelOrder(root) {
const res = [];
let q = root ? [root] : [];
while (q.length) {
const level = [], next = []; // this level, and the one below it
for (const node of q) {
level.push(node.val);
if (node.left) next.push(node.left);
if (node.right) next.push(node.right);
}
res.push(level);
q = next;
}
return res;
}
// complete tree: in BFS order, no real node may come after the first null
function isCompleteTree(root) {
const q = [root];
let head = 0, seenNull = false;
while (head < q.length) {
const node = q[head++];
if (!node) { seenNull = true; continue; }
if (seenNull) return false;
q.push(node.left, node.right);
}
return true;
} The variations
-
1Level by level
The size of the queue at the start of a round is the size of the level. The same loop links each node to the next one on its level.
Now you solve -
2Change the order of the levels
Run the normal BFS. For zigzag, reverse every other level list; for bottom-up, reverse the list of levels at the end.
Now you solve -
3Stop at the first gap
Push children even when they are null. In a complete tree, once you pop a null, every node after it must be null too.
-
4Run a check at every node
Visit every node of the big tree and ask "is the tree starting here the same as the small one?" with the same-tree check. O(m · n) worst case, which is fine for interview sizes.
Mistakes to avoid
- Reading
q.size()inside the for condition: it changes as you push children. Save it first. - Zigzag: reversing the order you push children breaks the next level. Keep BFS normal and reverse (or fill from the back) only the level list.
- In JavaScript,
q.shift()is O(n): use a head index or swap in a new array per level.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.