Command Palette

Search for a command to run...

Module 16

Binary Trees

Recursion on structure: depth-first orders, level-by-level BFS, returning values up the tree, and building trees from traversals.

Intermediate 5 lessons 12 problems ~65 min of lessons

A binary tree is recursion made visible: every node is the root of a smaller tree. Most tree problems become short once you decide what each call should return to its parent, and whether you need information from the children (post-order) or must pass information down (pre-order).

This module covers the vocabulary, the four traversals, breadth-first search by levels, the "return a value, update a global answer" pattern behind diameter and path sums, and constructing trees from traversal orders. Each dry run draws the actual tree.

Best after: Recursion, Queue, Deque and Monotonic Queue

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. The simplest post-order recursion: depth = 1 + the deeper subtree.

  2. Changing a tree's structure recursively: swap the children of every node.

  3. Recurse on two trees at once, comparing structure and values.

  4. Compare a tree with its own mirror: outer children with outer, inner with inner.

  5. Return height to the parent; record left + right as the best path through each node.

  6. Return a sentinel (−1) up the tree as soon as a subtree is unbalanced, keeping it O(n).

  7. The BFS template with level sizes.

  8. Per-level answers from BFS: the last node of each level is what you see from the right.

  9. Pass information down (the remaining sum) and check at the leaves.

  10. Post-order signals: each subtree reports whether it found p or q; the first node with reports from both sides is the LCA.

  11. Divide and conquer on traversals: the root splits the in-order list, and a hash map makes it O(n).

  12. Kadane's idea on a tree: each node returns its best one-sided gain (ignoring negative branches) and records the best two-sided path.