Trees & BSTs
Traverse trees and solve depth, path and BST problems.
By Invicly Tech, , in Interview Preparation. About 12 minutes to read.
In short
Tree problems are mostly about traversal: depth-first with recursion or breadth-first with a queue. In a binary search tree, every left value is smaller and every right value larger than the node.
Explained simply
A tree is like a family tree or a folder structure. There is one top node called the root. Each node can have children, and nodes with no children are called leaves. In a binary tree, each node has at most two children: left and right.
A binary search tree (BST) adds one rule: everything in a node's left side is smaller, and everything in its right side is bigger. That rule lets you find a value the way you look up a word in a dictionary: go left or right and ignore the other half.
Almost every tree problem is solved by visiting the nodes in some order. Depth-first search (DFS) goes all the way down one branch before trying the next. Breadth-first search (BFS) visits the tree level by level, like reading lines of text from top to bottom.
The trick that makes tree problems easy is trust. Assume your function already works for the left and right children, then decide how to combine their answers for the current node. With practice, most tree solutions become five or six lines.
Press Play on a diagram to walk through it one step at a time.
- 1Base case
Node is None: return a neutral value
- 2Solve left
Recurse into the left subtree
- 3Solve right
Recurse into the right subtree
- 4Combine
e.g. 1 + max(left, right) for depth
- 5Return upward
Parent uses this result
- Recursion or explicit stack
- Preorder, inorder, postorder
- Path sums, depth, LCA
- Space O(height)
- Queue, level by level
- Level order traversal
- Shortest depth, right side view
- Space O(widest level)
- 3 (left of 8: all smaller)
- 1
- 6
- 10 (right of 8: all bigger)
- 14
- Node, left, right
- Copy or serialise a tree
- Pass state down to children
- Left, node, right
- BST values in sorted order
- Kth smallest, validate BST
- Left, right, node
- Children answer first
- Height, diameter, delete tree
In depth
Iterative traversals with an explicit stack
Recursion uses the call stack, so a very deep or skewed tree (say 100,000 nodes in a line) can overflow it. Interviewers also like to ask for an iterative version to check you understand what recursion does for you.
Iterative inorder works like this: walk left as far as possible, pushing each node. Pop one, visit it, then move to its right child and repeat. Preorder is simpler: pop a node, visit it, push its right child and then its left child, so the left one comes out first. Postorder can be done by running a preorder that visits node, right, left and reversing the result.
- Inorder: push lefts, pop and visit, go right
- Preorder: pop, visit, push right then left
- Postorder: reverse of node, right, left
- 1Go left
Push every node while moving to the left child
- 2Pop
The top node has no unvisited left side
- 3Visit
Record its value
- 4Go right
Move to its right child
- 5Repeat
Until the stack is empty and the node is null
Passing values down vs returning values up
Tree recursions come in two flavours. Top-down solutions pass information down as parameters: the running path sum, the allowed min and max for a BST, or the current depth. Path Sum ("is there a root-to-leaf path adding to target?") is top-down: subtract the node's value and pass what is left.
Bottom-up solutions return information up: the height of a subtree, whether it is balanced, or its best path. The parent combines the children's answers. Diameter of a Binary Tree is bottom-up: each node returns its height, and along the way you update a global best of left height plus right height, because the longest path may bend at any node, not only at the root.
- State travels in parameters
- Decide at the leaves
- Path Sum, Validate BST bounds
- Like preorder
- Children return results
- Parent combines them
- Height, Diameter, Balanced Tree
- Like postorder
Lowest common ancestor
The lowest common ancestor (LCA) of nodes p and q is the deepest node that has both of them below it (a node counts as below itself). In a plain binary tree, recurse into both children. If you are at p or q, return yourself. If both the left and the right calls return something, p and q are on different sides, so this node is the LCA. Otherwise pass up whichever side found something. This is O(n) time.
In a BST you can do better using the ordering. Start at the root. If both values are smaller, go left. If both are bigger, go right. Otherwise they split here, or one of them is this node, so this is the LCA. That is O(h) time and O(1) space with a loop.
BST operations and their real cost
Search, insert and delete in a BST all cost O(h), where h is the height. In a balanced tree h is about log2(n), so a million nodes need about 20 steps. But a plain BST does not balance itself. Insert 1, 2, 3, 4, 5 in order and you get a straight line, so h = n and everything becomes O(n).
Deleting a node with two children is the classic tricky case: replace its value with its inorder successor (the smallest value in its right subtree), then delete that successor, which has at most one child. Real libraries use self-balancing trees. Java's TreeMap and TreeSet are red-black trees that guarantee O(log n) and give you floorKey, ceilingKey and ordered iteration for free.
- Balanced: about log2(n) levels
- Sorted inserts make a plain BST a linked list
- Kth smallest: stop the inorder walk at the kth node
Level by level with BFS
BFS uses a queue. The key trick for level problems is to read the queue size at the start of each round. Exactly that many nodes belong to the current level, so you process them in an inner loop while their children are added to the back of the queue for the next round.
With that one pattern you can solve Level Order Traversal (collect each level in a list), Right Side View (keep the last node of each level), Minimum Depth (return at the first leaf you meet, which BFS finds before going deeper) and Zigzag Order (reverse every other level). Space is O(w), where w is the widest level, which can be about n / 2 in a full tree.
Learn it in 6 short steps
About 1h 20m each. Track them with a timer in your plan.
- 1Implement DFS traversals recursively and iteratively~1h 20m
- 2Use BFS for level order~1h 20m
- 3Solve depth and path sum problems~1h 20m
- 4Validate and search a BST~1h 20m
- 5Practice: Max Depth, Lowest Common Ancestor~1h 20m
- 6Practice: Validate Binary Search Tree~1h 20m
Key points
- Most traversals are O(n) time, since each node is visited once.
- Inorder traversal of a BST yields values in sorted order.
- Validate a BST by passing allowed min and max bounds down, not just comparing children.
- Recursion depth equals tree height: O(log n) if balanced, O(n) if skewed.
Key terms
Tap a card to flip it. 0/5 known
Examples
def max_depth(root):
if not root:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))
def is_valid_bst(node, lo=float('-inf'), hi=float('inf')):
if not node:
return True
if not (lo < node.val < hi):
return False
return (is_valid_bst(node.left, lo, node.val) and
is_valid_bst(node.right, node.val, hi))Lowest Common Ancestor in a binary tree
Tree: 3 has children 5 and 1; 5 has children 6 and 2; 2 has children 7 and 4; 1 has children 0 and 8. For p = 5, q = 1: the call on node 5 returns 5 at once, the call on node 1 returns 1, and both sides of node 3 are non-null, so the answer is 3. For p = 5, q = 4: the left call on 3 returns 5 immediately (we never look below it), the right call finds nothing, so 5 is passed up. That is correct because 4 is below 5. One visit per node: O(n) time, O(h) stack.
TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) return root; // p and q split here
return left != null ? left : right; // pass up what was found
}Right Side View with level-order BFS
Imagine standing to the right of the tree. You see the last node of every level. Tree: 1 with children 2 and 3; 2 has a right child 5; 3 has a right child 4. Level 1 is [1], so you see 1. Level 2 is [2, 3]: the last is 3. Level 3 is [5, 4]: the last is 4. Answer [1, 3, 4]. The size snapshot tells you where each level ends, so you never need to store levels separately.
List<Integer> rightSideView(TreeNode root) {
List<Integer> out = new ArrayList<>();
if (root == null) return out;
Deque<TreeNode> queue = new ArrayDeque<>(); queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size(); // nodes on this level
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (i == size - 1) out.add(node.val); // last one on the level
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
return out; // O(n) time, O(width) space
}Quick reference
- Inorder of a BST is sorted; kth smallest is the kth node visited in order
- Level problems: take size = queue.size() before the inner loop
- Height-style answers (depth, diameter, balanced) return values up, like postorder
- Path and bound problems pass values down as parameters
- BST search, insert and delete cost O(h): O(log n) if balanced, O(n) if skewed
- Java TreeMap and TreeSet are red-black trees with floorKey and ceilingKey in O(log n)
- LCA in a BST: go left if both are smaller, right if both are bigger, else stop
Common mistakes
- Checking only node.left.val < node.val, which misses violations deeper down.
- Forgetting the empty tree case.
- Assuming a tree is balanced when stating recursion space.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Invert Binary Tree: swap the left and right child of every node.
- Exercise 2medium
Kth Smallest Element in a BST, without recursion.
- Exercise 3hard
Binary Tree Maximum Path Sum: the path can start and end at any nodes, and values can be negative.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is every binary tree a binary search tree?
- No. A binary tree only limits each node to two children. A BST also requires every value on the left to be smaller and every value on the right to be bigger, at every level.
- Should I write tree solutions recursively or iteratively?
- Start with recursion because it is shorter and clearer. Mention the O(h) stack cost, and switch to an iterative version if the interviewer asks or if the tree can be very deep.
- What is the difference between height and depth?
- Depth is measured from the root down to a node; height is measured from a node down to its deepest leaf. Some problems count edges and others count nodes (LeetCode's Maximum Depth counts nodes), so check the examples.
- How do I build a test tree from LeetCode's array format?
- The array lists nodes level by level, with null for missing children. Read it with a queue: take each node in turn and attach the next two array values as its left and right child.