Trees & BST · Pattern 1 of 12

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 · 12 with animated walkthroughs

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

When to use it

  • Visit every node in preorder, inorder or postorder
  • A value that is built from the two subtrees (depth, size, mirror)
  • Compare two trees, or a tree with itself mirrored
  • Do the same traversal without recursion, using a stack

The template

Recursion
int maxDepth(TreeNode root) {
    if (root == null) return 0;                               // empty tree: depth 0
    return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}

boolean isSameTree(TreeNode p, TreeNode q) {
    if (p == null || q == null) return p == q;                // true only if both are empty
    return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}

// recursive preorder: move out.add(...) between or after the calls for inorder / postorder
void preorder(TreeNode node, List<Integer> out) {
    if (node == null) return;
    out.add(node.val);
    preorder(node.left, out);
    preorder(node.right, out);
}

// iterative inorder: your own stack replaces the call stack
List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> res = new ArrayList<>();
    Deque<TreeNode> st = new ArrayDeque<>();
    TreeNode cur = root;
    while (cur != null || !st.isEmpty()) {
        while (cur != null) { st.push(cur); cur = cur.left; }   // go left as far as possible
        cur = st.pop();
        res.add(cur.val);                                       // visit
        cur = cur.right;                                        // then the right subtree
    }
    return res;
}

The variations

  1. 1Recursive traversals

    The same three lines in a different order: visit the node before the children (preorder), between them (inorder) or after them (postorder).

  2. 2Iterative traversals with a stack

    Push what the call stack would remember. Inorder goes left as far as it can, pops and turns right. Preorder pops a node and pushes the right child before the left one.

  3. 3Combine the two subtree answers

    Ask both children for their answer, then build yours: depth is 1 + max, a mirror swaps the children. The second minimum and the upside-down tree are the same idea with a different combine step.

  4. 4Walk two trees together

    Recurse on a pair of nodes. Both null is a match, one null is a mismatch, otherwise compare values and recurse on the matching pairs of children.

    Now you solve
  5. 5Carry a value down the path

    Pass what the path has built so far as a parameter (number * 10 + val) and add it to the answer at each leaf.

  6. 6More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Checking root.left.val before checking that root.left exists.
  • Symmetric tree: comparing left.left with right.left. A mirror pairs the outside children (left.left, right.right) and the inside ones.
  • Iterative postorder: the simple trick (preorder as node, right, left, then reverse) is fine, but say so; it uses O(n) extra space.

Mark it done once you can write the template from memory and you have solved the worked examples yourself.