Two templates, many problems
Recursive DFS (what does this node return?) solves most tree problems; BFS for levels and shortest steps, DFS with visited sets and topological sort for graphs.
- TreesInvert, symmetric, path sums and zigzag.
- GraphsTopological sort and multi-source BFS.
- HardClone graph and maximum path sum.
After arrays and strings, trees and graphs are the next most common coding-round topics. The solutions below follow two templates — recursive DFS for trees and BFS/DFS for graphs — that you can adapt to almost any variation.
1. Invert (mirror) a binary tree.
Swap the children of every node recursively. O(n).
TreeNode invert(TreeNode n) {
if (n == null) return null;
TreeNode left = invert(n.left);
n.left = invert(n.right);
n.right = left;
return n;
}2. Check whether a tree is symmetric.
Compare the left subtree with the mirror of the right: values equal, outer children mirrored, inner children mirrored.
boolean isSymmetric(TreeNode root) { return root == null || mirror(root.left, root.right); }
boolean mirror(TreeNode a, TreeNode b) {
if (a == null || b == null) return a == b;
return a.val == b.val && mirror(a.left, b.right) && mirror(a.right, b.left);
}3. Does a root-to-leaf path add up to a target?
Subtract each node's value on the way down; at a leaf, check whether the remainder is zero.
boolean hasPathSum(TreeNode n, int target) {
if (n == null) return false;
if (n.left == null && n.right == null) return target == n.val;
return hasPathSum(n.left, target - n.val) || hasPathSum(n.right, target - n.val);
}4. Zigzag level order traversal.
BFS by level, adding values left-to-right or right-to-left alternately (using a deque or reversing every other level).
List<List<Integer>> zigzag(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Deque<TreeNode> q = new ArrayDeque<>(List.of(root));
boolean leftToRight = true;
while (!q.isEmpty()) {
LinkedList<Integer> level = new LinkedList<>();
for (int i = q.size(); i > 0; i--) {
TreeNode n = q.poll();
if (leftToRight) level.addLast(n.val); else level.addFirst(n.val);
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
res.add(level);
leftToRight = !leftToRight;
}
return res;
}5. Course schedule: can all courses be finished given prerequisites?
A cycle in the prerequisite graph makes it impossible. Use Kahn's topological sort: if every course is processed, there is no cycle.
boolean canFinish(int n, int[][] prereq) {
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < n; i++) g.add(new ArrayList<>());
int[] indeg = new int[n];
for (int[] p : prereq) { g.get(p[1]).add(p[0]); indeg[p[0]]++; }
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n; i++) if (indeg[i] == 0) q.add(i);
int done = 0;
while (!q.isEmpty()) {
int c = q.poll(); done++;
for (int next : g.get(c)) if (--indeg[next] == 0) q.add(next);
}
return done == n;
}6. Rotting oranges: minutes until all oranges rot.
Multi-source BFS: start from every rotten orange at once; each BFS level is one minute. If fresh oranges remain, return −1.
int orangesRotting(int[][] g) {
Deque<int[]> q = new ArrayDeque<>();
int fresh = 0;
for (int r = 0; r < g.length; r++)
for (int c = 0; c < g[0].length; c++) {
if (g[r][c] == 2) q.add(new int[] { r, c });
else if (g[r][c] == 1) fresh++;
}
int minutes = 0;
int[][] dirs = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
while (!q.isEmpty() && fresh > 0) {
for (int i = q.size(); i > 0; i--) {
int[] cell = q.poll();
for (int[] d : dirs) {
int r = cell[0] + d[0], c = cell[1] + d[1];
if (r >= 0 && c >= 0 && r < g.length && c < g[0].length && g[r][c] == 1) {
g[r][c] = 2; fresh--; q.add(new int[] { r, c });
}
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
}7. Clone a graph.
DFS or BFS with a map from original node to its copy, so each node is copied once and cycles are handled.
Map<Node, Node> copies = new HashMap<>();
Node cloneGraph(Node node) {
if (node == null) return null;
if (copies.containsKey(node)) return copies.get(node);
Node copy = new Node(node.val);
copies.put(node, copy);
for (Node nb : node.neighbors) copy.neighbors.add(cloneGraph(nb));
return copy;
}8. Find the maximum path sum in a binary tree (any node to any node).
Each call returns the best downward path from that node; at each node, update a global best with left + node + right, ignoring negative branches.
int best = Integer.MIN_VALUE;
int maxPathSum(TreeNode root) { gain(root); return best; }
int gain(TreeNode n) {
if (n == null) return 0;
int left = Math.max(0, gain(n.left)), right = Math.max(0, gain(n.right));
best = Math.max(best, n.val + left + right);
return n.val + Math.max(left, right);
}Remember
Key points
- Return value per node
The heart of tree recursion.
- Global best + local return
For path-sum style problems.
- Multi-source BFS
Start from all sources at once.
- Map original → copy
Handles cycles when cloning.
Interview drill
Follow-up questions
What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.
-
1 How do you check whether a tree is height-balanced in O(n)? Intermediate
Return the height from each call, or −1 if a subtree is unbalanced, and stop early.
-
2 Right side view of a binary tree. Intermediate
BFS by level and take the last node of each level (or DFS visiting right first, recording the first node per depth).
-
3 Number of connected components in an undirected graph. Basic
Count how many times you start a new DFS/BFS from an unvisited node, or use union-find.
-
4 Word ladder: shortest transformation sequence. Advanced
BFS over words, generating neighbours by changing one letter at a time and checking a dictionary set.
-
5 Construct a tree from preorder and inorder traversals. Advanced
The first preorder value is the root; its index in inorder splits left and right subtrees. Use a map from value to inorder index for O(n).
-
6 Detect a cycle in an undirected graph. Intermediate
DFS tracking the parent — visiting an already-visited node that is not the parent means a cycle; or union-find.