Trees: Tree recursion, traversal, and BST invariants
Goal: Learn the pattern first, then apply it to the 15 roadmap problems in this chapter.
When this pattern appears
A result is composed from child results, nodes are visited by level, or ordered tree properties guide search.
The reusable idea
Choose a return value that summarizes a subtree. Separate values returned upward from global answers.
A deliberate problem-solving routine
- Write the input and output in plain language. Identify whether order, duplicates, or mutation matter.
- Work a tiny example by hand; label the state you wish you had at each step.
- Choose the structure or invariant that stores that state.
- Establish a brute-force baseline, then show exactly which repeated work the pattern removes.
- State the invariant before the loop, after each iteration, and at termination.
- Test smallest, boundary, duplicate, and adversarial cases.
Watch the animated pattern
The diagram above this lesson animates the core state changes for this chapter. Use pause and step to predict what moves next. The same invariant should explain each application, even when the problem story changes.
Questions to ask yourself
What exact summary can a child return that lets its parent solve its part?
Common failure modes
Null-tree base cases, nodes-versus-edges, ancestor-wide BST bounds, and negative values.
Chapter problems from the workbook
- #51 · Invert Binary Tree — Day 30, Easy. Open problem ↗
- #52 · Maximum Depth of Binary Tree — Day 30, Easy. Open problem ↗
- #53 · Same Tree — Day 30, Easy. Open problem ↗
- #54 · Diameter of Binary Tree — Day 31, Easy. Open problem ↗
- #55 · Balanced Binary Tree — Day 31, Easy. Open problem ↗
- #56 · Subtree of Another Tree — Day 31, Easy. Open problem ↗
- #57 · Lowest Common Ancestor of a BST — Day 32, Medium. Open problem ↗
- #58 · Binary Tree Level Order Traversal — Day 32, Medium. Open problem ↗
- #59 · Binary Tree Right Side View — Day 33, Medium. Open problem ↗
- #60 · Count Good Nodes in Binary Tree — Day 33, Medium. Open problem ↗
- #61 · Validate Binary Search Tree — Day 34, Medium. Open problem ↗
- #62 · Kth Smallest Element in a BST — Day 34, Medium. Open problem ↗
- #63 · Construct Binary Tree from Preorder and Inorder — Day 36, Medium. Open problem ↗
- #64 · Binary Tree Maximum Path Sum — Day 36, Hard. Open problem ↗
- #65 · Serialize and Deserialize Binary Tree — Day 37, Hard. Open problem ↗
Interview explanation
A concise explanation has four parts: the key observation, the maintained invariant, why each step preserves it, and the time/space complexity. Avoid naming a pattern as a substitute for proving the step is safe.