Interview practice: binary trees, BSTs and heaps in Java
Patterns for tree and heap interview problems: ask both children then combine, level-order BFS, BST validation with a min-max range, top-K with a min-heap, median with two heaps, TreeMap for nearest ranges; plus the stack overflow and overflowing comparator traps.
On this page
1. The problem
A candidate writes isValidBST comparing each node with its two children, passes 3 sample tests, then fails the 4th. AI-written code with new PriorityQueue<>((a, b) -> b - a) works for months, then misorders once large negative numbers show up. Neither bug throws.
2. Key idea
Most tree problems use one pattern: ask both children, combine at the current node, O(n). A BST (binary search tree): every node in the left subtree is smaller and the right subtree larger, so inorder gives ascending order. A heap is a nearly complete tree stored in an array with the smallest element at the root (min-heap): peek O(1), add or remove O(log n).
| The task says | Pattern | Complexity |
|---|---|---|
| height, diameter, LCA | postorder recursion | O(n) time, O(h) stack |
| by level, distance from root | BFS, read queue.size() before the for loop |
O(n) |
| validate BST, kth smallest | inorder or a (low, high) range |
O(n), can stop early |
| K largest, K most frequent | min-heap of size K | O(n log K) |
| merge K sorted lists | heap holding each list's head | O(N log K) |
| median of a stream | max-heap for the low half + min-heap for the high half | O(log n) per number |
| Structure | Use when | Don't use when |
|---|---|---|
PriorityQueue |
you keep needing the smallest (or largest) | you remove arbitrary elements: remove(o) is O(n) |
TreeMap/TreeSet |
"nearest to x", non-overlapping room bookings | you only need the smallest |
| Full sort | you need complete order | K is much smaller than n, or the data is a stream |
3. In Java
static boolean isValidBST(TreeNode n, long low, long high) { // call with Long.MIN_VALUE, Long.MAX_VALUE
if (n == null) return true;
if (n.val <= low || n.val >= high) return false; // long: handles Integer.MIN_VALUE
return isValidBST(n.left, low, n.val) && isValidBST(n.right, n.val, high);
}
static int kthLargest(int[] nums, int k) { // [3,2,1,5,6,4], k=2 -> 5
PriorityQueue<Integer> heap = new PriorityQueue<>(); // min-heap
for (int x : nums) {
heap.offer(x);
if (heap.size() > k) heap.poll(); // drop the smallest
}
return heap.peek();
}
PriorityQueue<Integer> max = new PriorityQueue<>(Comparator.reverseOrder()); // not b - aIterating a PriorityQueue with for-each or toString() isn't sorted; only repeated poll() is. Other languages: Python's heapq is min-heap only (negate for a max-heap); Go has container/heap.
4. Working with AI
Hand to AI: generating random trees and 100,000-node skewed trees for tests, turning a recursive version into an ArrayDeque loop, comparing results with a brute-force version.
Check yourself in AI-written code:
- BST validation passes a range down, with
longbounds. - Comparators use
Integer.compareorComparator.reverseOrder(), never subtraction. - User-built trees (nested comments, categories) have a loop version or a depth limit.
- Tests cover an empty tree, one node, a skewed tree,
Integer.MIN_VALUE/MAX_VALUE.
5. Exercises
Exercise 1: Review isValidBST
The AI says "O(n), tested on 3 sample trees". Find a tree that breaks it, then fix it.
static boolean isValidBST(TreeNode n) {
if (n == null) return true;
if (n.left != null && n.left.val >= n.val) return false;
if (n.right != null && n.right.val <= n.val) return false;
return isValidBST(n.left) && isValidBST(n.right);
}Solution 1
Tree: root 5, left 4, right 6, and 6 has a left child 3. Every parent–child pair is fine, but 3 sits in the right subtree of 5. The function returns true; the answer is false.
Fix: pass a (low, high) range as in section 3. Alternative: inorder traversal checking strictly increasing values.
Exercise 2: Choose how to get the top 10
A table of 50 million events; you need today's 10 best-selling products. The AI offers: (A) load everything into Java and sort; (B) load everything into Java with a size-10 min-heap; (C) GROUP BY product_id ORDER BY total DESC LIMIT 10 in the database. Pick one, give the reason and when the choice flips.
Solution 2
- Pick (C): when the data is in the database, let the database aggregate instead of pulling 50 million rows over the network. A suitable index or a daily summary table makes it faster still.
- (B) beats (A) once the data is in the application: O(n log 10) time and O(10) memory versus O(n log n) and the whole array.
- Switch to (B) when the data is a stream (Kafka, logs) not in a database: each event touches the heap once.
Exercise 3: Median of a stream
Design a class with addNum(int) and findMedian(), called alternately millions of times. State the idea and complexity before asking an AI for code.
Solution 3
The low half in a max-heap low, the high half in a min-heap high; low has at most one more element than high. addNum is O(log n), findMedian O(1).
PriorityQueue<Integer> low = new PriorityQueue<>(Comparator.reverseOrder());
PriorityQueue<Integer> high = new PriorityQueue<>();
void addNum(int x) {
low.offer(x);
high.offer(low.poll()); // largest of the low half moves up
if (high.size() > low.size()) low.offer(high.poll());
}
double findMedian() {
return low.size() > high.size() ? low.peek() : (low.peek() + (long) high.peek()) / 2.0;
}Verify against a re-sort-after-every-number version on 10,000 random numbers. The (long) avoids overflow when adding two large values.
Summary
- Tree problems: ask both children then combine, O(n); by level means BFS.
- BST validation: pass a
(low, high)range withlongbounds. - K largest: a min-heap of size K.
- Median of a stream: two heaps differing by at most one element.
- No subtraction in comparators; skewed trees need a loop version.
Further reading: Graphs and dynamic programming.
Self-compiled notes from official documentation and hands-on practice.
Comments
Community rules