Skip to main content
Back to all problems
Beginner guide, Algorithms & data structures

Trees

Recursion on trees: DFS, BFS, and what a binary search tree guarantees.

A tree is a structure made of nodes connected like a family tree, upside down: one node at the top (the root), and each node can have children below it. In a binary tree, each node has at most two children: a left child and a right child.

The words you'll see

text
        3          ← root (no parent)
       / \
      9   20       ← 9 and 20 are children of 3; 3 is their parent
         /  \
        15   7     ← leaves (no children)
WordMeaning
rootthe top node
leafa node with no children
subtreea node together with everything below it
depth / levelhow far a node is from the root (the root is level 0)
heightthe number of levels (here 3). Written h in complexities
ancestorany node on the path from the root down to a node

What a node looks like

js
class TreeNode {
  constructor(val = 0, left = null, right = null) {
    this.val = val // the value stored in this node
    this.left = left // left child, or null
    this.right = right // right child, or null
  }
}

The problems give you TreeNode already. In the tests, trees are written level by level with null for a missing child: [3, 9, 20, null, null, 15, 7] is the tree above.

The big idea: recursion

A tree is a node plus two smaller trees (its left and right subtrees). That's why almost every tree problem is solved with recursion: a function that calls itself on the subtrees.

The question to ask every time:

"If a recursive call already gave me the answer for the left subtree and the right subtree, how do I get the answer for this node?"

Then add a base case, usually the empty tree (null). Example, counting the nodes:

js
function count(node) {
  if (!node) return 0 // base case: an empty tree has 0 nodes
  return 1 + count(node.left) + count(node.right) // me + left + right
}

Trust the recursive calls: you don't need to trace them all the way down. Most tree solutions are 3 to 6 lines that follow this exact shape.

Two ways to visit every node

Depth-first search (DFS)

Go deep down one branch before trying the next. That's what recursion naturally does. There are three orders, depending on when you handle the node itself:

OrderVisitsFor the tree aboveTypical use
preordernode, left, right3, 9, 20, 15, 7copying or saving a tree
inorderleft, node, right9, 3, 15, 20, 7reading a BST in sorted order
postorderleft, right, node9, 15, 7, 20, 3computing from the children up (depth, sums)

Breadth-first search (BFS)

Go wide: visit the tree level by level, using a queue. The trick to know where a level ends: the children of one level, in order, are the next level.

js
let level = root ? [root] : []
while (level.length > 0) {
  // ... handle every node in `level` ...
  const next = []
  for (const node of level) {
    if (node.left) next.push(node.left)
    if (node.right) next.push(node.right)
  }
  level = next
}

Use BFS when the problem talks about levels or the closest/shallowest something.

Binary search trees (BST)

A BST is a binary tree with an ordering rule, at every node:

  • everything in the left subtree is smaller;
  • everything in the right subtree is larger.
text
      5
     / \
    3   8
   / \    \
  1   4    9

Two consequences you'll use:

  1. You can search like binary search: compare with the current node and go left or right. That's O(h) instead of O(n) (Lowest Common Ancestor of a BST).
  2. An inorder traversal visits the values in sorted order (Validate BST, Kth Smallest in a BST).

How fast is it?

  • Visiting every node once: O(n) time.
  • Recursion uses memory for the call stack: O(h). For a balanced tree h is about log n; for a tree that's one long chain, h = n.

How to recognize the approach

  • "Compute something about the whole tree" (depth, sums, same/mirror): DFS recursion, combining answers from the children.
  • "Level by level", "each level", "closest to the root": BFS with a queue.
  • The tree is a BST: use the ordering, either to walk one path down, or with inorder for sorted order.
  • The answer at a node depends on its ancestors (like allowed ranges): pass that information down as parameters.

Common mistakes

  • Forgetting the base case and reading .left of null.
  • Checking only a node and its direct children when the rule is about whole subtrees (the classic Validate BST trap).
  • Overwriting a child before using it, for example when swapping. Save it in a variable first.
  • Confusing "return" with "record". Sometimes what a node returns to its parent differs from the best answer it sees (Binary Tree Maximum Path Sum).

Practice what you learned

The problems go from easier to harder. Try each one on your own and open a hint when you get stuck.