Trees & BST · Lesson

Binary trees and BSTs, explained: traversals, recursion and every pattern

Learn binary trees and BSTs: traversals, BFS, views, LCA, tree DP, serialization and BST operations, with templates in Java, Python, C++ and JavaScript.

12 patterns · 81 problems · Java, Python, C++ and JavaScript

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

What a binary tree is

A binary tree is a set of nodes where each node has a value and at most two children, left and right. The top node is the root; nodes with no children are leaves. Every node is the root of its own smaller tree, its subtree.

That last fact is why trees and recursion fit so well. To solve a problem for a tree, solve it for the left subtree, solve it for the right subtree, and combine the two answers at the node. Most tree code is ten lines once you decide what each call returns to its parent.

The height h decides the cost of anything that walks one path: h is about log n when the tree is balanced, but n when it is a long chain. Visiting every node is always O(n).

What a binary search tree adds

A binary search tree (BST) keeps one rule at every node: everything in the left subtree is smaller, everything in the right subtree is bigger. So an inorder traversal (left, node, right) reads the values in sorted order.

The rule lets you throw away half the tree at each step, like binary search: search, insert, floor and ceil each walk a single path, O(h). The catch is that the rule is about whole subtrees, not just the parent and child, which is the classic bug when validating a BST.

How to pick the pattern

  • Something per level, or the nearest node: BFS with a queue, one level at a time.
  • Something per path from the root: DFS that carries the path or a running value down, and undoes it on the way back.
  • Something per subtree (height, sum, is it valid): postorder; each call returns what the parent needs, and you record the global best on the side.
  • Move up as well as down (distance k, burning): store each node's parent and treat the tree as a graph.
  • The tree is a BST: use the order. Walk one path, or use inorder as a sorted list.

What it costs

OperationTimeSpace
Visit every node (any traversal)O(n)O(h) stack or O(w) queue
Height, size, sum of a treeO(n)O(h)
BST search / insert / deleteO(h): O(log n) balanced, O(n) skewedO(1) iterative
Kth smallest in a BST (inorder, stop early)O(h + k)O(h)
Build from preorder + inorder (with a map)O(n)O(n)
Balanced BST from a sorted arrayO(n)O(log n)

Built into your language

Library calls
class TreeNode { int val; TreeNode left, right; TreeNode(int v) { val = v; } }

Deque<TreeNode> q = new ArrayDeque<>();   // BFS queue: offer / poll / size (no nulls allowed)
Deque<TreeNode> st = new ArrayDeque<>();  // DFS stack: push / pop / peek

// Java's built-in balanced BST
TreeMap<Integer, String> map = new TreeMap<>();
map.put(5, "a"); map.put(2, "b");
map.floorKey(4);      // 2: largest key <= 4
map.ceilingKey(4);    // 5: smallest key >= 4
map.firstKey();       // 2

Mistakes everyone makes

  • Forgetting the null base case: every recursive tree function must handle an empty subtree first.
  • Validating a BST by comparing a node only with its parent. Each node must fit a (min, max) range set by all its ancestors.
  • Mixing up what a call returns to its parent with what it records globally (diameter, max path sum).
  • Assuming the tree is balanced: a skewed tree makes recursion O(n) deep and can overflow the stack.
  • Adding a shared path list to the answer without copying it, then changing it as the recursion goes on.

The 12 patterns, in order

Each one: the idea and template, its variations with a worked example, then problems for you to solve.

  1. 1 Tree recursion: traversals, depth and comparing trees Handle null, recurse on the left and right subtrees, and combine their answers at the node. Preorder, inorder and postorder only differ in when you visit the node. 6 variations · 15 problems
  2. 2 Backtracking on trees: root-to-leaf paths and path sums Add the node to a shared path, recurse into both children, then remove it on the way back. The path always holds exactly the nodes from the root to where you are. 2 variations · 3 problems
  3. 3 Level order traversal: BFS one level at a time Put the root in a queue. Each round, read the queue size, pop exactly that many nodes and push their children: those nodes are one level. 4 variations · 7 problems
  4. 4 Tree views: left, right, top, bottom and vertical order Give every node a coordinate: its level, and a column (left child col - 1, right child col + 1). Each view keeps one node per level or per column; BFS order decides which one. 4 variations · 7 problems
  5. 5 BST basics: search, insert, delete and build At every node, the value you want is either here, on the left or on the right, so you walk one path down. Inorder visits the values in sorted order. 5 variations · 12 problems
  6. 6 Postorder with multiple return values: tree DP Solve both children first, then the node. Each call returns what its parent needs (height, a sum, a pair of states), and the real answer is often recorded on the side. 5 variations · 12 problems
  7. 7 Lowest common ancestor: in a binary tree and in a BST Ask both subtrees whether they contain p or q. The first node where the answers come from different sides (or the node is one of them) is the lowest common ancestor. 3 variations · 6 problems
  8. 8 Child and ancestor handling: the tree as a graph A node only knows its children. Record every node's parent first, then you can move in three directions (left, right, up) and run BFS from any node. 3 variations · 4 problems
  9. 9 Inorder and reverse inorder: kth smallest and largest Inorder (left, node, right) visits a BST in increasing order; reverse inorder (right, node, left) visits it in decreasing order. Count the nodes as you go and stop at the kth. 1 variation · 2 problems
  10. 10 Build a tree from traversals, and serialize it Preorder tells you the root first; inorder tells you which values are left of it. Serializing is the same idea in reverse: write a traversal with markers for null, then read it back in the same order. 3 variations · 5 problems
  11. 11 Tree to list and back: flatten, DLL and sorted list to BST Pick the traversal order the list must follow and keep a pointer to the last node you linked. Linking each new node to that one rewires the tree in place. 3 variations · 3 problems
  12. 12 Floor, ceil, successor and predecessor in a BST Walk one path from the root. Every time you move away from a node that could be the answer, remember it as the best candidate so far. 3 variations · 5 problems