Lesson 15 of 40Trees and graphs
Trees
Walk binary trees depth-first and level by level, and solve tree problems with one recursive template.
Your file system is a tree. So is the DOM in every web page, the JSON a server sends you, and the index inside your database. Tree questions are also the single most common topic in coding interviews, because they test recursion, which is the skill most people find hardest to fake. So far most structures in this track have been sequences: arrays, strings, stacks and linked lists. From here on, each node can lead to several others.
The good news: almost every tree problem is solved by the same short template. Learn to walk a tree and that template, and a whole category of problems opens up.
The words you need
A tree is a set of nodes connected by links, with no loops. Each node holds a value and points to its children.
- The root is the single node at the top. It has no parent.
- A leaf is a node with no children.
- The depth of a node is how many links it is from the root (the root has depth 0).
- The height of a tree is the number of nodes on the longest path from the root down to a leaf. A single node has height 1, an empty tree height 0. (Some books count links instead of nodes, so always say which one you mean.)
- A subtree is any node plus everything below it. Every child is the root of its own subtree, which is why recursion fits trees so well.
A binary tree is a tree where each node has at most two children, called left and right. In code, a node is a tiny class:
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = rightclass TreeNode {
constructor(
public val: number,
public left: TreeNode | null = null,
public right: TreeNode | null = null,
) {}
}Interview problems write trees as a list in level order, top to bottom and left to right, with null for missing children. [4, 2, 6, 1, 3, 5, 7] is a root of 4, children 2 and 6, and four leaves.
Depth-first traversals
To traverse a tree is to visit every node once. Depth-first search (DFS) goes as deep as possible down one branch before backing up. There are three orders, and they differ only in when you handle the current node compared to its children:
| Order | Visit | On [4, 2, 6, 1, 3, 5, 7] | Typical use |
|---|---|---|---|
| Pre-order | node, left, right | 4 2 1 3 6 5 7 | Copy or serialise a tree |
| In-order | left, node, right | 1 2 3 4 5 6 7 | Read a BST in sorted order |
| Post-order | left, right, node | 1 3 2 5 7 6 4 | Compute something from the children first (height, size, delete) |
Watch in-order on our tree. The rule at every node is the same: finish the whole left subtree, then the node, then the right subtree.
Start at the root, 4. In-order says: left subtree first, so we do not output 4 yet.
In code, the three orders are the same function with one line moved:
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Pre-order (node, left, right) on the tree [1, 2, 3, null, 4]: node 1 has children 2 and 3, and node 2 has only a right child, 4. What is printed?
def preorder(node):
if node is None:
return
print(node.val, end=" ")
preorder(node.left)
preorder(node.right)
preorder(root)The recursive template
Most tree problems fit one shape: solve for the left subtree, solve for the right subtree, combine. You trust the recursive call to return the right answer for a smaller tree, and only think about one node.
Maximum depth (the height) is the classic example. The height of a tree is 1 for this node plus the taller of its two subtrees. An empty tree has height 0.
def max_depth(root):
if root is None: # base case: empty tree
return 0
left = max_depth(root.left) # solve for left
right = max_depth(root.right) # solve for right
return 1 + max(left, right) # combinefunction maxDepth(root: TreeNode | null): number {
if (root === null) return 0; // base case: empty tree
const left = maxDepth(root.left); // solve for left
const right = maxDepth(root.right); // solve for right
return 1 + Math.max(left, right); // combine
}That is post-order: children first, then the node. Swap the "combine" line and you get other classics. Count nodes: 1 + left + right. Same tree: compare values, then both pairs of subtrees. Invert a tree: swap left and right, then recurse into both.
Every node is visited once, so these run in O(n) time. The recursion stack holds one frame per level, so space is O(h), where h is the height: O(log n) for a balanced tree, O(n) for a tree that is one long chain.
Put the lines of a recursive tree function in order.
- Tap the steps below in the right order.
Breadth-first: level by level
Sometimes you need the tree one level at a time: the right-side view, the average of each level, the shortest path to a leaf. That is breadth-first search (BFS), and it uses a queue (first in, first out) instead of recursion.
The trick for grouping by level: at the start of each round, the queue holds exactly one level. Record its length, pop that many nodes, and push their children for the next round.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Use collections.deque in Python: list.pop(0) shifts every element and costs O(n). JavaScript has no built-in deque, so the TypeScript version builds the next level in a fresh array instead of calling shift() (which is also O(n)).
Binary search trees
A binary search tree (BST) adds one rule: for every node, everything in its left subtree is smaller and everything in its right subtree is larger. Our tree [4, 2, 6, 1, 3, 5, 7] is a BST, which is why in-order printed it sorted.
The rule lets you search like binary search: compare with the node, then throw away half the tree.
def bst_contains(node, target):
while node:
if target == node.val:
return True
node = node.left if target < node.val else node.right
return FalseEach step goes one level down, so a search costs O(h). In a balanced tree, where the two sides of every node have roughly the same height, h is about log₂ n: a million nodes need about 20 comparisons. But insert 1, 2, 3, 4, 5 in order and every node goes to the right. The "tree" is a linked list, h = n, and search is O(n). Real libraries use self-balancing trees (red-black, AVL, B-trees in databases) to keep h at O(log n).
Practice
Start with maximum depth, which is the template in its purest form. Then try level order. When you are comfortable, the practice section has invert-tree (swap children at every node) and validate-bst (pass a valid range down the recursion).
Maximum Depth of a Binary Tree
Given the root of a binary tree, return its maximum depth: the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0.
Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.
[3, 9, 20, null, null, 15, 7] → 3 (3 -> 20 -> 15)
[1, null, 2] → 2
[] → 0Constraints
0 <= number of nodes <= 10^4-100 <= Node.val <= 100
Level Order Traversal
Given the root of a binary tree, return its values level by level: a list of lists, where each inner list holds one level's values from left to right.
Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.
[3, 9, 20, null, null, 15, 7] → [[3], [9, 20], [15, 7]]
[1] → [[1]]
[] → []Constraints
0 <= number of nodes <= 2000-1000 <= Node.val <= 1000
- root / leaf
- The root is the top node with no parent. A leaf is a node with no children.
- height
- Number of nodes on the longest root-to-leaf path. Recursion and BST operations cost O(h).
- pre / in / post-order
- DFS orders that handle the node before, between, or after its children. In-order on a BST gives sorted output.
- level-order (BFS)
- Visit the tree one level at a time using a queue. Snapshot
len(queue)to group by level. - binary search tree
- Every value in a node's left subtree is smaller and every value in its right subtree is larger.
- balanced tree
- Subtree heights stay close, so h is O(log n). An unbalanced BST can degrade to a chain with O(n) search.