Trees & BSTs

Traversals iterative and recursive, BST invariants, LCA, serialize/deserialize. Recursion confidence is built here or nowhere.

About 32 min read3-question knowledge check

The mental model

A tree is an org chart. One person at the top (the root), each person reports to exactly one boss (the parent), and each has some number of direct reports (children). There are no loops — you cannot be your own great-grandboss — and there is exactly one path from the CEO to any employee. That "exactly one path, no cycles" property is what makes a tree a tree rather than a general graph, and it is what makes recursion so natural on trees: solve the problem for your subordinates, then combine.

A binary search tree adds one rule to the org chart that turns it into a search engine: for every person, everyone in their left sub-org has a smaller key and everyone in their right sub-org has a larger key. That single invariant means finding any key is a game of "warmer/colder": start at the root, and at each node go left if your target is smaller, right if larger. Each step throws away half the remaining tree — the same halving that makes binary search on a sorted array O(log n), but a balanced BST can insert and delete in O(log n) too, which a sorted array cannot.

Why do trees exist? Because hierarchy is everywhere — file systems, the DOM, org structures, parse trees, decision trees — and because the halving property gives you the best of both worlds an array and a linked list each only half-deliver: an array searches in O(log n) but inserts in O(n); a linked list inserts in O(1) but searches in O(n); a balanced BST does both in O(log n). That is the pitch.

The interview reality: trees are where recursion confidence is built or nowhere. Almost every tree problem is "do something to the root, recurse on the children, combine the results", and if recursion feels shaky, tree problems feel impossible. The flip side is that once the recursive shape clicks, a huge family of problems — traversals, height, diameter, lowest common ancestor, validation, serialization — all fall to the same three-line skeleton. The caveat the mental model must include, and the thing that separates a mid answer from a senior one: a BST is only O(log n) if it is balanced. Insert sorted data into a naive BST and it degenerates into a linked list — O(n) per operation — which is exactly why self-balancing trees (AVL, red-black) exist.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision