Video in progress
How do you output a binary tree level by level, with each level as a separate list?
With BFS, but at the start of each iteration I remember the queue size: that many nodes belong exactly to the current level. I take them, write them into one list and add their children to the queue. O(n).
📖 Answer
static List<List<Integer>> levels(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Deque<TreeNode> q = new ArrayDeque<>();
q.offer(root);
while (!q.isEmpty()) {
int size = q.size(); // number of nodes on the current level
List<Integer> level = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
TreeNode n = q.poll();
level.add(n.val());
if (n.left() != null) q.offer(n.left());
if (n.right() != null) q.offer(n.right());
}
result.add(level);
}
return result;
}
The key trick is taking size before the inner loop. If you call q.size() inside the loop, it grows with the newly added children and the levels get mixed up.
Many problems come from this template:
- the depth of the tree is
result.size(); - "the nodes visible from the right side" are the last one on each level;
- zigzag order means reversing every other level;
- the average value of each level.
ArrayDeque doesn't accept null, so the null check before adding a child is mandatory.
Sign up to mark studied questions and save your progress.