Binary Tree Practice Problems
How to Use This Problem List
Binary tree problems look diverse but follow a small number of structural patterns. The key skill is recognising which of four thinking modes a problem belongs to:
MODE 1 — TOP-DOWN (Preorder thinking): Pass information from parent to children. Decision at each node uses data from ancestors. Example: check if path sum equals target MODE 2 — BOTTOM-UP (Postorder thinking): Collect information from children to compute parent. Decision at each node uses results from descendants. Example: height, diameter, balanced check MODE 3 — LEVEL AWARENESS (BFS thinking): Need to process or compare nodes at the same depth. Example: right side view, zigzag traversal, max width MODE 4 — STRUCTURAL (Inorder thinking): BST-specific — inorder gives sorted order. Example: validate BST, kth smallest
Identify the mode before writing code. The implementation follows mechanically from the correct mode.
Pattern 1: Tree Metrics — Height, Size, Depth
Properties of the tree that require visiting every node once. All are O(n) time with O(h) space.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Maximum Depth of Binary Tree | Easy | "height of tree", "maximum depth" | Postorder: 1 + max(height(L), height(R)); base null→0 |
| Minimum Depth of Binary Tree | Easy | "minimum depth", "nearest leaf" | BFS finds nearest leaf first; or DFS: leaf→1, single child→go deeper |
| Count Complete Tree Nodes | Medium | "count nodes in complete binary tree" | Exploit completeness: compare left/right heights; O(log² n) |
| Count Nodes in Binary Tree | Easy | "total nodes in tree" | Postorder: 1 + count(L) + count(R) |
| Sum of All Node Values | Easy | "sum of all node values" | Any traversal: val + sum(L) + sum(R) |
| Maximum Width of Binary Tree | Medium | "maximum width between leftmost and rightmost" | BFS + column indices; normalise to prevent overflow |
| Deepest Leaves Sum | Medium | "sum of deepest level nodes" | BFS: sum last level; or DFS: track max depth |
| Find Largest Value in Each Row | Medium | "maximum value at each level" | BFS: max per level using levelSize trick |
Complexity target: O(n) time, O(h) space. O(log² n) time for Complete Tree Nodes.
Recognition signal: "depth", "height", "count", "sum of all", "width", "level". A single numeric property of the entire tree or each level.
Pattern 2: Path Problems
A path is a sequence of nodes from some starting node downward or between any two nodes. Always think about what information flows along the path.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Path Sum | Easy | "any root-to-leaf path sums to target" | Top-down: subtract val each level; base at leaf: remaining==node.val |
| Path Sum II (all paths) | Medium | "find all root-to-leaf paths summing to target" | Backtracking: add to path, recurse, pop after return |
| Path Sum III (any subpath) | Medium | "paths summing to target starting from any node" | Prefix sum map: count paths ending here using seen prefix sums |
| Binary Tree Maximum Path Sum | Hard | "maximum path sum, path between any two nodes" | Postorder: at each node track one-side contribution; update global max |
| Sum Root to Leaf Numbers | Medium | "integer formed by root-to-leaf digits" | Top-down: pass accumulated number × 10 + val |
| Count Good Nodes in Tree | Medium | "node is good if no larger value on path from root" | Top-down: pass max-so-far; count if node.val ≥ max |
| Binary Tree Paths | Easy | "all root-to-leaf paths as strings" | Backtracking: build string path, record at leaf |
| Pseudo-Palindromic Paths | Medium | "paths where digits can form a palindrome" | XOR bitmask: track odd-count digits; at leaf: at most one bit set |
Complexity target: O(n) time, O(h) space for stack/recursion.
Recognition signal: "root-to-leaf", "path sum", "any path", "digits along path". Something accumulates as you travel from node to node.
Pattern 3: Tree Structure — Shape, Symmetry, Balance
Problems about the structural shape of the tree independent of values.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Symmetric Tree | Easy | "mirror image of itself" | Recursive: isMirror(left, right) — values match AND left.left ↔ right.right |
| Same Tree | Easy | "are two trees identical" | All three must match: val, left subtree, right subtree |
| Balanced Binary Tree | Easy | "height-balanced — subtrees differ by at most 1" | Postorder: return -1 if unbalanced; propagate -1 up |
| Diameter of Binary Tree | Easy | "longest path between any two nodes" | Postorder: at each node: diameter = L_height + R_height; track global max |
| Flip Equivalent Binary Trees | Medium | "can flip children to make trees identical" | At each node: try both — no flip (L≡L, R≡R) or flip (L≡R, R≡L) |
| Subtree of Another Tree | Easy | "is T a subtree of S" | For each node in S: isSameTree(node, T) |
| Merge Two Binary Trees | Easy | "merge by summing overlapping nodes" | Postorder: if either null return other; merge values, recurse |
| Invert Binary Tree | Easy | "flip tree horizontally" | Postorder: swap left and right, then recurse into each |
| Check Completeness of Binary Tree | Medium | "is tree a complete binary tree" | BFS: once a non-full node seen, all subsequent must be leaves |
Complexity target: O(n) time, O(h) space. Subtree check is O(S×T) naive or O(S+T) with hashing.
Recognition signal: "symmetric", "same", "balanced", "flip", "subtree", "complete", "invert". The problem asks about the tree's shape or structural relationship.
Pattern 4: Tree Construction and Transformation
Build a tree from given data, or transform an existing tree into a different form.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Construct Tree from Preorder + Inorder | Medium | "rebuild tree from preorder and inorder arrays" | Preorder[0] = root; find root in inorder to split left/right |
| Construct Tree from Postorder + Inorder | Medium | "rebuild tree from postorder and inorder arrays" | Postorder[-1] = root; same inorder split logic |
| Construct Tree from Level Order | Medium | "rebuild from BFS sequence" | BFS construction: pair each parent with next two nodes in queue |
| Flatten Binary Tree to Linked List | Medium | "flatten to right-skewed list in preorder" | Postorder trick: flatten right, flatten left, attach left before right |
| Populating Next Right Pointers | Medium | "connect level nodes horizontally" | BFS level order; or clever O(1) pointer threading |
| Serialize and Deserialize Binary Tree | Hard | "convert tree to string and back" | Preorder with null markers; deserialize using a queue/index |
| Convert Sorted Array to BST | Easy | "sorted array → height-balanced BST" | Mid element as root; recurse on left and right halves |
| Convert BST to Greater Tree | Medium | "each node's value += sum of all greater nodes" | Reverse inorder (right→root→left): accumulate running sum |
Complexity target: O(n) time, O(n) space (for output or reconstruction).
Recognition signal: "construct", "build", "flatten", "serialize", "convert". The problem creates a new tree or restructures an existing one.
Pattern 5: Lowest Common Ancestor (LCA) and Ancestors
Problems involving ancestors, paths between nodes, and finding common nodes.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Lowest Common Ancestor (General) | Medium | "deepest node that is ancestor of both p and q" | Return node when found; LCA where both sub-results are non-null |
| LCA of BST | Easy | "LCA in BST (values matter)" | Use BST property: if both < root → go left; both > root → go right; else root is LCA |
| Kth Ancestor of Tree Node | Medium | "kth ancestor of given node" | Binary lifting: precompute ancestors at power-of-2 jumps |
| Distance Between Two Nodes | Medium | "shortest path length between two nodes" | LCA first; distance = depth(p) + depth(q) - 2×depth(LCA) |
| All Nodes at Distance K | Medium | "all nodes exactly k edges from target" | Build parent map via BFS; then BFS from target with distance tracking |
| Nodes in Subtree With Given Label | Medium | "count nodes in subtree with specific label" | Postorder: accumulate label counts; return count for parent |
Complexity target: O(n) time O(n) space preprocessing; O(log n) per query with binary lifting.
Recognition signal: "common ancestor", "path between nodes", "distance from", "k edges away". The problem requires tracing paths upward or between nodes.
Pattern 6: Level-Based Problems (BFS)
Problems where the answer depends on which level a node is on, or requires processing nodes in level order.
| Problem | Difficulty | Recognition Clue | Key Insight |
|---|---|---|---|
| Binary Tree Level Order Traversal | Medium | "collect nodes level by level" | levelSize = queue.size() before inner loop |
| Binary Tree Zigzag Level Order | Medium | "zigzag, alternating direction per level" | Toggle direction flag; addFirst/addLast on deque |
| Binary Tree Right Side View | Medium | "rightmost node at each level" | Last node dequeued per level (i == levelSize-1) |
| Binary Tree Left Side View | Easy | "leftmost node at each level" | First node dequeued per level (i == 0) |
| Average of Levels | Easy | "average value at each level" | Sum per level / levelSize |
| Level Order Bottom | Easy | "levels from leaf to root" | Standard BFS then reverse result |
| Minimum Level Sum | Easy | "level with minimum sum" | BFS: compute sum per level; track minimum |
| Find Bottom Left Tree Value | Medium | "leftmost node in the deepest level" | BFS: first node of last level |
| Cousins in Binary Tree | Easy | "two nodes at same level with different parents" | BFS: track depth and parent; cousins if same depth, different parent |
Complexity target: O(n) time, O(w) space where w = max level width.
Recognition signal: "level", "each row", "level by level", "depth k", "rightmost/leftmost at depth". Anything about nodes at the same horizontal position.
Recommended Study Order
Week 1 — Foundations Pattern 1 (Metrics): Max Depth, Min Depth, Count Nodes Pattern 3 (Structure): Symmetric Tree, Same Tree, Invert Binary Tree Week 2 — Core DFS Patterns Pattern 2 (Paths): Path Sum, Binary Tree Paths, Path Sum II Pattern 3 (Structure): Balanced Binary Tree, Diameter of Binary Tree Week 3 — Intermediate Pattern 5 (Ancestors): LCA of Binary Tree, LCA of BST Pattern 4 (Build): Construct from Preorder+Inorder, Flatten Tree Pattern 6 (BFS): Level Order, Zigzag, Right Side View Week 4 — Hard Problems Pattern 2 (Paths): Binary Tree Maximum Path Sum, Path Sum III Pattern 4 (Build): Serialize and Deserialize Binary Tree Pattern 5 (Ancestors): All Nodes at Distance K, Distance Between Two Nodes Revisit any pattern that felt unclear
Problem-Solving Checklist for Binary Tree Problems
Before writing code, answer these questions:
1. IDENTIFY THE THINKING MODE
□ Top-down (preorder): does each node need info from its parent?
□ Bottom-up (postorder): does each node need results from children?
□ Level-based (BFS): does position (level/column) matter?
□ Structural (inorder + BST): does order of values matter?
2. DEFINE WHAT THE RECURSIVE FUNCTION RETURNS
□ A single value (height, count, sum)?
□ A boolean (is balanced, are same)?
□ A node (LCA, first occurrence)?
□ Multiple values (use a global variable or tuple/pair return)?
3. WRITE THE BASE CASES FIRST
□ null node — what to return? (0 for height, true for symmetry, null for LCA)
□ leaf node — any special case beyond null?
4. WRITE THE RECURSIVE CASE
□ What does left subtree contribute?
□ What does right subtree contribute?
□ How are they combined at the current node?
5. CHECK FOR GLOBAL STATE
□ Does the answer require updating a variable across all nodes?
(diameter, max path sum, count of nodes)
□ If yes: use a class-level variable or a single-element array/list
6. EDGE CASES
□ Empty tree (null root)
□ Single node tree (root only, no children)
□ All nodes on one side (skewed tree)
□ Negative values (for path sum problems)
Pattern Recognition Quick Reference
| Signal in Problem | Pattern | Thinking Mode |
|---|---|---|
| "height", "maximum depth" | Tree metrics | Bottom-up postorder |
| "root-to-leaf path sum" | Path problems | Top-down preorder |
| "any path between nodes" | Path problems | Postorder + global max |
| "symmetric", "mirror" | Structure | Postorder pairwise comparison |
| "diameter", "longest path" | Structure | Postorder + global max |
| "balanced", "height diff" | Structure | Postorder with -1 sentinel |
| "lowest common ancestor" | Ancestors | Postorder: return node when found |
| "level by level", "each row" | Level-based | BFS with levelSize trick |
| "rightmost/leftmost at each level" | Level-based | BFS, first or last per level |
| "construct from traversals" | Construction | Split via inorder root position |
| "flatten to linked list" | Transformation | Postorder + pointer threading |
| "serialize/deserialize" | Construction | Preorder with null markers |
Difficulty Progression Reference
| Stage | Characteristics | Representative Problems |
|---|---|---|
| Foundation | Single postorder/preorder, O(n) | Max Depth, Invert Tree, Same Tree |
| Early Intermediate | Global variable, balanced check | Diameter, Balanced Binary Tree, Path Sum |
| Intermediate | Path tracking, BFS level tricks | Path Sum II, LCA, Level Order Zigzag |
| Late Intermediate | Multi-pass, construction | Construct from Traversals, Flatten Tree |
| Advanced | Hard paths, complex construction | Max Path Sum, Serialize/Deserialize, All Nodes K |
Common Interview Topics by Company Focus
Product-based companies (FAANG-tier):
- ›Binary Tree Maximum Path Sum — the canonical hard tree problem
- ›Serialize and Deserialize Binary Tree — design + recursion
- ›Construct Binary Tree from Preorder + Inorder — fundamental construction
- ›Diameter of Binary Tree — postorder global max pattern
- ›LCA of Binary Tree — ancestor traversal
- ›All Nodes at Distance K — multi-technique combination
- ›Symmetric Tree — pairwise structural comparison
Service-based and on-campus:
- ›Max Depth, Min Depth, Invert Tree — postorder basics
- ›Level Order, Right Side View — BFS patterns
- ›Path Sum, Path Sum II — path accumulation
- ›Same Tree, Subtree of Another Tree — structural comparison
Startup and mid-size tech:
- ›Flatten Binary Tree to Linked List — in-place transformation
- ›Populating Next Right Pointers — O(1) space BFS
- ›Count Good Nodes — top-down with running max
- ›Binary Tree Paths — backtracking with string path
Progress Tracking
After solving each problem, record:
- ›Thinking mode — top-down, bottom-up, BFS, or inorder?
- ›What the recursive function returned — value, boolean, node, or tuple?
- ›Base cases used — null → ? and leaf → ?
- ›Global variable needed? — and what did it track?
- ›Edge cases caught or missed — null root? Single node? Negative values?
- ›Time to solve — target 15-20 minutes for easy, 25-30 for medium under interview conditions
The decisive signal that pattern recognition is working: when you see "diameter of binary tree" and immediately think "postorder — at each node, left_height + right_height updates global max, return 1 + max(left, right) to parent" — before reading the constraints or examples.
Problem: find the height of a binary tree. Which traversal and return value pattern should you use?