DSA Tutorial
🔍

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.

ProblemDifficultyRecognition ClueKey Insight
Maximum Depth of Binary TreeEasy"height of tree", "maximum depth"Postorder: 1 + max(height(L), height(R)); base null→0
Minimum Depth of Binary TreeEasy"minimum depth", "nearest leaf"BFS finds nearest leaf first; or DFS: leaf→1, single child→go deeper
Count Complete Tree NodesMedium"count nodes in complete binary tree"Exploit completeness: compare left/right heights; O(log² n)
Count Nodes in Binary TreeEasy"total nodes in tree"Postorder: 1 + count(L) + count(R)
Sum of All Node ValuesEasy"sum of all node values"Any traversal: val + sum(L) + sum(R)
Maximum Width of Binary TreeMedium"maximum width between leftmost and rightmost"BFS + column indices; normalise to prevent overflow
Deepest Leaves SumMedium"sum of deepest level nodes"BFS: sum last level; or DFS: track max depth
Find Largest Value in Each RowMedium"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.

ProblemDifficultyRecognition ClueKey Insight
Path SumEasy"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 SumHard"maximum path sum, path between any two nodes"Postorder: at each node track one-side contribution; update global max
Sum Root to Leaf NumbersMedium"integer formed by root-to-leaf digits"Top-down: pass accumulated number × 10 + val
Count Good Nodes in TreeMedium"node is good if no larger value on path from root"Top-down: pass max-so-far; count if node.val ≥ max
Binary Tree PathsEasy"all root-to-leaf paths as strings"Backtracking: build string path, record at leaf
Pseudo-Palindromic PathsMedium"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.

ProblemDifficultyRecognition ClueKey Insight
Symmetric TreeEasy"mirror image of itself"Recursive: isMirror(left, right) — values match AND left.left ↔ right.right
Same TreeEasy"are two trees identical"All three must match: val, left subtree, right subtree
Balanced Binary TreeEasy"height-balanced — subtrees differ by at most 1"Postorder: return -1 if unbalanced; propagate -1 up
Diameter of Binary TreeEasy"longest path between any two nodes"Postorder: at each node: diameter = L_height + R_height; track global max
Flip Equivalent Binary TreesMedium"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 TreeEasy"is T a subtree of S"For each node in S: isSameTree(node, T)
Merge Two Binary TreesEasy"merge by summing overlapping nodes"Postorder: if either null return other; merge values, recurse
Invert Binary TreeEasy"flip tree horizontally"Postorder: swap left and right, then recurse into each
Check Completeness of Binary TreeMedium"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.

ProblemDifficultyRecognition ClueKey Insight
Construct Tree from Preorder + InorderMedium"rebuild tree from preorder and inorder arrays"Preorder[0] = root; find root in inorder to split left/right
Construct Tree from Postorder + InorderMedium"rebuild tree from postorder and inorder arrays"Postorder[-1] = root; same inorder split logic
Construct Tree from Level OrderMedium"rebuild from BFS sequence"BFS construction: pair each parent with next two nodes in queue
Flatten Binary Tree to Linked ListMedium"flatten to right-skewed list in preorder"Postorder trick: flatten right, flatten left, attach left before right
Populating Next Right PointersMedium"connect level nodes horizontally"BFS level order; or clever O(1) pointer threading
Serialize and Deserialize Binary TreeHard"convert tree to string and back"Preorder with null markers; deserialize using a queue/index
Convert Sorted Array to BSTEasy"sorted array → height-balanced BST"Mid element as root; recurse on left and right halves
Convert BST to Greater TreeMedium"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.

ProblemDifficultyRecognition ClueKey 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 BSTEasy"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 NodeMedium"kth ancestor of given node"Binary lifting: precompute ancestors at power-of-2 jumps
Distance Between Two NodesMedium"shortest path length between two nodes"LCA first; distance = depth(p) + depth(q) - 2×depth(LCA)
All Nodes at Distance KMedium"all nodes exactly k edges from target"Build parent map via BFS; then BFS from target with distance tracking
Nodes in Subtree With Given LabelMedium"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.

ProblemDifficultyRecognition ClueKey Insight
Binary Tree Level Order TraversalMedium"collect nodes level by level"levelSize = queue.size() before inner loop
Binary Tree Zigzag Level OrderMedium"zigzag, alternating direction per level"Toggle direction flag; addFirst/addLast on deque
Binary Tree Right Side ViewMedium"rightmost node at each level"Last node dequeued per level (i == levelSize-1)
Binary Tree Left Side ViewEasy"leftmost node at each level"First node dequeued per level (i == 0)
Average of LevelsEasy"average value at each level"Sum per level / levelSize
Level Order BottomEasy"levels from leaf to root"Standard BFS then reverse result
Minimum Level SumEasy"level with minimum sum"BFS: compute sum per level; track minimum
Find Bottom Left Tree ValueMedium"leftmost node in the deepest level"BFS: first node of last level
Cousins in Binary TreeEasy"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 ProblemPatternThinking Mode
"height", "maximum depth"Tree metricsBottom-up postorder
"root-to-leaf path sum"Path problemsTop-down preorder
"any path between nodes"Path problemsPostorder + global max
"symmetric", "mirror"StructurePostorder pairwise comparison
"diameter", "longest path"StructurePostorder + global max
"balanced", "height diff"StructurePostorder with -1 sentinel
"lowest common ancestor"AncestorsPostorder: return node when found
"level by level", "each row"Level-basedBFS with levelSize trick
"rightmost/leftmost at each level"Level-basedBFS, first or last per level
"construct from traversals"ConstructionSplit via inorder root position
"flatten to linked list"TransformationPostorder + pointer threading
"serialize/deserialize"ConstructionPreorder with null markers

Difficulty Progression Reference

StageCharacteristicsRepresentative Problems
FoundationSingle postorder/preorder, O(n)Max Depth, Invert Tree, Same Tree
Early IntermediateGlobal variable, balanced checkDiameter, Balanced Binary Tree, Path Sum
IntermediatePath tracking, BFS level tricksPath Sum II, LCA, Level Order Zigzag
Late IntermediateMulti-pass, constructionConstruct from Traversals, Flatten Tree
AdvancedHard paths, complex constructionMax 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:

  1. Thinking mode — top-down, bottom-up, BFS, or inorder?
  2. What the recursive function returned — value, boolean, node, or tuple?
  3. Base cases used — null → ? and leaf → ?
  4. Global variable needed? — and what did it track?
  5. Edge cases caught or missed — null root? Single node? Negative values?
  6. 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.

Suggested Quiz

Problem: find the height of a binary tree. Which traversal and return value pattern should you use?

1/6
Binary Tree Practice Problems