Skip to content

Lesson 15 of 40Trees and graphs

Trees

Walk binary trees depth-first and level by level, and solve tree problems with one recursive template.

18 min read0/5 questions

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 = right

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.

[4, 2, 6, 1, 3, 5, 7]
1234567
Quick check
In the tree above, what is the depth of node 5, and what is the height of the whole tree (counting nodes)?
Need a nudge? A hint rules out a wrong answer.

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:

OrderVisitOn [4, 2, 6, 1, 3, 5, 7]Typical use
Pre-ordernode, left, right4 2 1 3 6 5 7Copy or serialise a tree
In-orderleft, node, right1 2 3 4 5 6 7Read a BST in sorted order
Post-orderleft, right, node1 3 2 5 7 6 4Compute 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.

In-order traversal
1234567

result:

Start at the root, 4. In-order says: left subtree first, so we do not output 4 yet.

1/6

In code, the three orders are the same function with one line moved:

Python
class TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def inorder(node, out): if node is None: return inorder(node.left, out) out.append(node.val) # move this line up for pre-order, down for post-order inorder(node.right, out) root = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(6, TreeNode(5), TreeNode(7)))result = []inorder(root, result)print(result)
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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)     # 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 it in order4 steps

Put the lines of a recursive tree function in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Python
from collections import deque class TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def level_order(root): if root is None: return [] levels, queue = [], deque([root]) while queue: level = [] for _ in range(len(queue)): # exactly one level node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) levels.append(level) return levels root = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))print(level_order(root))
Output
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)).

Quick check
You need the minimum depth of a tree (the shortest root-to-leaf path) and the tree may be very deep on one side. Which approach can stop earliest?
Need a nudge? A hint rules out a wrong answer.

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 False

Each 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).

Quick check
Is this a valid BST? Root 5, left child 3, right child 8, and 3 has a right child 6.
Need a nudge? A hint rules out a wrong answer.

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).

ChallengeEasy

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
[]                             →  0

Constraints

  • 0 <= number of nodes <= 10^4
  • -100 <= Node.val <= 100
# The harness already defines TreeNode:# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = right def max_depth(root: TreeNode | None) -> int: # The depth of a tree is 1 + the deeper of its two subtrees. pass
ChallengeMedium

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
# The harness already defines TreeNode:# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = right def level_order(root: TreeNode | None) -> list[list[int]]: # Use a queue and process the tree one whole level at a time. pass
Key terms
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.
Interview pattern: Trees39 problemsSpot it: Hierarchies · depth · paths · BST ordering