Return the level-order traversal of a binary tree, and its right side view.
Problem
Return the node values level by level ([[3],[9,20],[15,7]]), and the right side view (the last node of each level: [3,20,7]).
Approach
Breadth-first search with a queue. Process the tree one level at a time by recording the queue size at the start of each level.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
class LevelOrder {
record TreeNode(int val, TreeNode left, TreeNode right) {
TreeNode(int val) { this(val, null, null); }
}
static List<List<Integer>> levels(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Deque<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size(); // nodes on this level
List<Integer> level = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
level.add(node.val());
if (node.left() != null) queue.offer(node.left());
if (node.right() != null) queue.offer(node.right());
}
result.add(level);
}
return result;
}
static List<Integer> rightSideView(TreeNode root) {
return levels(root).stream().map(l -> l.get(l.size() - 1)).toList();
}
public static void main(String[] args) {
TreeNode root = new TreeNode(3, new TreeNode(9), new TreeNode(20, new TreeNode(15), new TreeNode(7)));
System.out.println(levels(root)); // [[3], [9, 20], [15, 7]]
System.out.println(rightSideView(root)); // [3, 20, 7]
}
}Complexity
O(n) time; O(w) queue space, where w is the maximum width of the tree.
Follow-up questions interviewers ask
Try answering each one before you open it.
How would you do a zigzag level order traversal?
Same BFS, but alternate direction per level: add values to the level list from the front (addFirst on a LinkedList/ArrayDeque) on odd levels and from the back on even levels, or reverse every other level list. O(n).
How do you compute the maximum depth, iteratively and recursively?
Recursively: depth(node) = node == null ? 0 : 1 + max(depth(left), depth(right)), which uses O(h) stack and can overflow on very deep (degenerate) trees. Iteratively: count the number of levels in the BFS above. Use the iterative form when depth may be large.