Trees & BST
Core idea
Section titled “Core idea”Think recursively: “If I magically had the answer for my left and right subtrees, how would I build the answer for this node?” Then handle the base case (null).
public class TreeNode { int val; TreeNode left, right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; }}Templates
Section titled “Templates”// DFS template: return info up the treeint dfs(TreeNode node) { if (node == null) return 0; // base case int left = dfs(node.left); int right = dfs(node.right); // combine, maybe update a global answer return /* info for the parent */ 1 + Math.max(left, right);}
// BFS level-order templateQueue<TreeNode> q = new ArrayDeque<>();if (root != null) q.offer(root);while (!q.isEmpty()) { int size = q.size(); // freeze the size = one level for (int i = 0; i < size; i++) { TreeNode node = q.poll(); if (node.left != null) q.offer(node.left); if (node.right != null) q.offer(node.right); }}Traversals
Section titled “Traversals”| Order | Sequence | Used for |
|---|---|---|
| Preorder | node, left, right | Copying/serializing a tree |
| Inorder | left, node, right | BST → sorted order |
| Postorder | left, right, node | Deleting, computing heights/diameters |
| Level order | BFS | Shortest depth, per-level views |
Problem: Binary Tree Traversals, Recursive + Iterative (Easy) — LC 144 / 94 / 145
Approach (say out loud): “Recursion is three lines. Iteratively I simulate the call stack with an explicit stack. For inorder: go as far left as possible pushing nodes, pop and visit, then go right. Postorder trick: do a modified preorder (node, right, left) and reverse it.”
Java:
class Traversals { // Recursive void preorder(TreeNode n, List<Integer> out) { if (n == null) return; out.add(n.val); preorder(n.left, out); preorder(n.right, out); } void inorder(TreeNode n, List<Integer> out) { if (n == null) return; inorder(n.left, out); out.add(n.val); inorder(n.right, out); } void postorder(TreeNode n, List<Integer> out) { if (n == null) return; postorder(n.left, out); postorder(n.right, out); out.add(n.val); }
// Iterative preorder List<Integer> preorderIter(TreeNode root) { List<Integer> out = new ArrayList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); if (root != null) stack.push(root); while (!stack.isEmpty()) { TreeNode n = stack.pop(); out.add(n.val); if (n.right != null) stack.push(n.right); // right first so left is processed first if (n.left != null) stack.push(n.left); } return out; }
// Iterative inorder List<Integer> inorderIter(TreeNode root) { List<Integer> out = new ArrayList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode curr = root; while (curr != null || !stack.isEmpty()) { while (curr != null) { // go all the way left stack.push(curr); curr = curr.left; } curr = stack.pop(); out.add(curr.val); curr = curr.right; } return out; }
// Iterative postorder: (node, right, left) reversed = (left, right, node) List<Integer> postorderIter(TreeNode root) { LinkedList<Integer> out = new LinkedList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); if (root != null) stack.push(root); while (!stack.isEmpty()) { TreeNode n = stack.pop(); out.addFirst(n.val); if (n.left != null) stack.push(n.left); if (n.right != null) stack.push(n.right); } return out; }}Complexity: O(n) time, O(h) space (h = height: log n if balanced, n if skewed)
Edge cases: an empty tree, a skewed tree (deep recursion can overflow the stack for about 10^5 nodes, which is a good reason to know the iterative version).
Problems
Section titled “Problems”Problem: Binary Tree Level Order Traversal (Medium) — LC 102
Approach (say out loud): “BFS with a queue. I capture q.size() at the start of each level so I know exactly how many nodes belong to that level.”
Java:
class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); Queue<TreeNode> q = new ArrayDeque<>(); if (root != null) q.offer(root); while (!q.isEmpty()) { int size = q.size(); List<Integer> level = new ArrayList<>(); for (int i = 0; i < size; i++) { TreeNode node = q.poll(); level.add(node.val); if (node.left != null) q.offer(node.left); if (node.right != null) q.offer(node.right); } res.add(level); } return res; }}Complexity: O(n) time, O(w) space, where w is the max width (up to n/2)
Edge cases: an empty tree → []. Variants: right side view (last of each level), zigzag (reverse alternate levels).
Problem: Maximum Depth of Binary Tree (Easy) — LC 104
Approach (say out loud): “The depth of a node is 1 plus the max of its children’s depths. A null node has depth 0.”
Java:
class Solution { public int maxDepth(TreeNode root) { if (root == null) return 0; return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); }}Complexity: O(n) time, O(h) space
Edge cases: an empty tree → 0, a single node → 1.
Problem: Invert Binary Tree (Easy) — LC 226
Approach (say out loud): “Swap the left and right children, then recurse into both.”
Java:
class Solution { public TreeNode invertTree(TreeNode root) { if (root == null) return null; TreeNode tmp = root.left; root.left = invertTree(root.right); root.right = invertTree(tmp); return root; }}Complexity: O(n) time, O(h) space
Edge cases: null root.
Problem: Diameter of Binary Tree (Easy) — LC 543
Approach (say out loud): “The longest path through a node = left height + right height. My DFS returns the height to the parent, and on the side it updates a global best with left + right. This is the ‘return one thing, record another’ pattern.”
Java:
class Solution { private int best = 0;
public int diameterOfBinaryTree(TreeNode root) { height(root); return best; }
private int height(TreeNode node) { if (node == null) return 0; int l = height(node.left); int r = height(node.right); best = Math.max(best, l + r); // path through this node (in edges) return 1 + Math.max(l, r); }}Complexity: O(n) time, O(h) space
Edge cases: the longest path may not pass through the root. A single node → 0.
Problem: Lowest Common Ancestor of a Binary Tree (Medium) — LC 236
Approach (say out loud): “If the current node is p or q, return it. Otherwise I search both sides. If both sides return something non-null, p and q are split across me, so I’m the LCA. If only one side does, I pass that result up.”
Java:
class Solution { public 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; return left != null ? left : right; }}Complexity: O(n) time, O(h) space
Edge cases: p is an ancestor of q (return p). For a BST (LC 235): if both values are smaller, go left. If both are bigger, go right. Otherwise the current node is the LCA, in O(h).
Problem: Validate Binary Search Tree (Medium) — LC 98
Approach (say out loud): “Checking only left < node < right locally is a trap. Every node must fit within a range inherited from its ancestors. I pass down (min, max) bounds and use long so Integer.MIN_VALUE/MAX_VALUE nodes work.”
Java:
class Solution { public boolean isValidBST(TreeNode root) { return valid(root, Long.MIN_VALUE, Long.MAX_VALUE); }
private boolean valid(TreeNode node, long min, long max) { if (node == null) return true; if (node.val <= min || node.val >= max) return false; return valid(node.left, min, node.val) && valid(node.right, node.val, max); }}Complexity: O(n) time, O(h) space
Edge cases: duplicates are invalid here (strict), node values at the int limits. Alternative: an inorder traversal must be strictly increasing.
Problem: Search and Insert in a BST (Easy/Medium) — LC 700 / 701
Approach (say out loud): “In a BST, smaller values go left and bigger go right, so I follow a single path, O(h). For insert, I walk down to a null spot and attach the new node there.”
Java:
class Solution { public TreeNode searchBST(TreeNode root, int val) { while (root != null && root.val != val) { root = val < root.val ? root.left : root.right; } return root; }
public TreeNode insertIntoBST(TreeNode root, int val) { if (root == null) return new TreeNode(val); if (val < root.val) root.left = insertIntoBST(root.left, val); else root.right = insertIntoBST(root.right, val); return root; }}Complexity: O(h) time: O(log n) if balanced, O(n) if skewed. Search is O(1) space. Recursive insert is O(h) space.
Edge cases: an empty tree (insert returns the new root), a value not present (search returns null).
Problem: Kth Smallest Element in a BST (Medium) — LC 230
Approach (say out loud): “Inorder traversal of a BST visits values in sorted order. I do an iterative inorder and stop at the kth pop.”
Java:
class Solution { public int kthSmallest(TreeNode root, int k) { Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode curr = root; while (curr != null || !stack.isEmpty()) { while (curr != null) { stack.push(curr); curr = curr.left; } curr = stack.pop(); if (--k == 0) return curr.val; curr = curr.right; } return -1; }}Complexity: O(h + k) time, O(h) space
Edge cases: k = 1 (the leftmost node), k = n (the rightmost).
Problem: Serialize and Deserialize Binary Tree (Hard) — LC 297 (basics)
Approach (say out loud): “Preorder DFS, writing # for null children so the structure is unambiguous. To deserialize, I read tokens in the same preorder from a queue: a # means null, otherwise I create the node and recursively build its left, then its right.”
Java:
public class Codec { public String serialize(TreeNode root) { StringBuilder sb = new StringBuilder(); build(root, sb); return sb.toString(); }
private void build(TreeNode node, StringBuilder sb) { if (node == null) { sb.append("#,"); return; } sb.append(node.val).append(','); build(node.left, sb); build(node.right, sb); }
public TreeNode deserialize(String data) { Queue<String> tokens = new ArrayDeque<>(Arrays.asList(data.split(","))); return parse(tokens); }
private TreeNode parse(Queue<String> tokens) { String t = tokens.poll(); if (t.equals("#")) return null; TreeNode node = new TreeNode(Integer.parseInt(t)); node.left = parse(tokens); node.right = parse(tokens); return node; }}Complexity: O(n) time and space for both
Edge cases: an empty tree serializes to "#,", negative values (fine since we split on commas).