Pattern

Binary search trees

Use the ordering invariant of a BST to prune half the tree or read it in sorted order, instead of a generic tree walk.

What it is

A binary search tree adds one structural promise on top of a plain binary tree: every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger. That single invariant is what lets you skip an entire subtree during a search instead of visiting every node, and it means an inorder traversal (left, node, right) visits values in strictly ascending order for free. BST problems are really about spending that invariant deliberately — deciding at each node which side can be ignored, or exploiting the fact that "in sorted order" and "inorder traversal" mean the same thing here.

When it applies

Tells in the problem

The classic mistake

Validating a BST by only checking a node against its immediate children (left child smaller, right child larger) instead of against the full range of values that are allowed at that position — a node three levels down in a left subtree must be smaller than every ancestor above it that it's under the left side of, not just its direct parent, so a local check misses violations from higher up. The general BST mistake this generalizes to: using the invariant only one level deep instead of carrying the accumulated bound (a valid (low, high) range, passed down and narrowed at each step) through the whole recursion. Notice this in yourself whenever a BST solution compares only to node.val or node.left.val without also referencing bounds inherited from further up the tree.

Questions to start with

All 4 binary search trees questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.