Maximum Depth of Binary Tree

Count the nodes on the longest path from the root of a binary tree down to a leaf.

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, which is a node with no children. An empty tree has depth 0.

Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: 3
Explanation: the path 3 → 20 → 15 has three nodes, and no path is longer.
Example 2
Input: root = [1, null, 2]
Output: 2
Solution

The Idea

Think of folders on a computer: a folder holds other folders, and those hold more. How many folders deep does the deepest one sit? A binary tree asks the same question, except that each node holds at most two others, a left child and a right child.

The examples write a tree row by row, with null for a missing child. In Example 1, [3, 9, 20, null, null, 15, 7], the top node 3 is the root, and its children are 9 and 20. The two null values say that 9 has no children, and the last two values give 20 its children, 15 and 7.

The nodes 9, 15 and 7 have no children, so they are the leaves. Three paths run from the root down to a leaf: 3 → 9 has two nodes, while 3 → 20 → 15 and 3 → 20 → 7 have three each. The longest has three nodes, so the answer is 3.

Writing out every path works for five nodes, but a big tree has a great many paths, and they all share the nodes near the top. Is there a way to get the answer without listing them?

Look at where the longest path from 3 goes. After the root it continues either into 9 or into 20. Node 20 together with everything below it forms a smaller tree of its own, called a subtree, and so does 9 alone. If we knew how deep each of those two subtrees is, the whole tree would be one deeper than the deeper of them, because the root adds one node on top.

The same rule works for each subtree, and for the subtrees inside it, until a side is empty. An empty side has no nodes, so its depth is 0. Look at the picture below, where every node shows its depth, worked out from the bottom up.

The tree of Example 1 with each node's depth. The leaves 9, 15 and 7 have depth 1, node 20 has depth 1 + max(1, 1) = 2, and the root 3 has depth 1 + max(1, 2) = 3. The path 3, 20, 15 is highlighted.

Under 9, both sides are empty and each counts 0, so 9 gets depth 1 + max(0, 0) = 1. The leaves 15 and 7 get depth 1 the same way. Node 20 then gets 1 + max(1, 1) = 2, and the root, at the top, gets 1 + max(1, 2) = 3. The highlighted path 3 → 20 → 15 is where that 3 comes from.

So the depth of a tree is 1 plus the larger depth of its two subtrees. A method that answers a question by calling itself on smaller parts of the input is called recursive. Here each node waits for the answers from both children before it works out its own, and visiting the children before the node is called a postorder traversal (see Trees Basics).

Solution Approach

Turning that rule into code means settling three things: what an empty side returns, how a node combines its two sides, and how many calls wait at the same time. Counting the tree row by row comes last, as an optional alternative.

The empty side

Where does the method stop calling itself? At a missing child, which Java holds as null, and the method returns 0 there, because there are no nodes to count. A leaf then gets 1 + max(0, 0) = 1 with no special check for leaves, and an empty input tree gets 0 directly.

Some textbooks count the lines between nodes, called edges, instead of the nodes, and name the result the height. That version returns -1 for an empty side. Run on Example 1, it returns 2, not 3, so this problem needs the 0.

Combining the two sides

Why ask both children? The deeper side can be either one, and the method cannot tell which without asking. In Example 2, [1, null, 2], the root 1 has only a right child, 2. The empty left side gives 0, the right side gives 1, and the root gets 1 + max(0, 1) = 2.

Every node below the root is asked once, by its parent, and its answer is passed straight up. Writing out every path, by contrast, counts the root and the nodes near it again for each leaf below them.

How many calls wait at once

How much does the method keep in memory? A call that is waiting for its children stays open until they answer, and the open calls always form one path down from the root. So at most as many calls wait at once as the tree is deep.

For a tree like [1, 2, 3, 4, 5, 6, 7], where every row is full, that is small. A tree in which each node has only a left child is one long chain, and every node waits at the same time. Java gives each thread a limited block of memory for open calls, called the stack. In a test run, a chain of 1,000 nodes worked, while a chain of 1,000,000 nodes ended with a StackOverflowError.

Counting rows instead (optional)

For trees that may be that deep, the depth can be counted without calling the method on itself. A queue is a waiting line: items come out in the order they went in. Put the root in a queue, then repeatedly take out every node of the current row, put in their children, and add 1 to a row count. When the queue is empty, the row count is the depth. The queue holds at most one row at a time, and no calls wait on the stack.

Java Solution

The method maxDepth works in these steps:

  1. First, check whether root is null. If it is, the tree is empty, so return 0.
  2. Otherwise, call maxDepth(root.left) to get the depth of the left subtree and keep it in left. Do the same for the right subtree and keep the result in right.
  3. Return 1 + Math.max(left, right): this node on top of the deeper side.

Around the method, the class has a short TreeNode class, a build helper that turns the row-by-row form into nodes, and a run helper that prints each input with its depth. The main method tries both examples, an empty tree, a single node, a chain that leans left, and a tree with three full rows.

Java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;

public class MaxDepthBinaryTree {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    public static int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;                         // an empty tree has no nodes
        }
        int left = maxDepth(root.left);       // deepest path on the left side
        int right = maxDepth(root.right);     // deepest path on the right side
        return 1 + Math.max(left, right);     // this node on top of the deeper side
    }

    // Builds a tree from the row-by-row form, where null marks a missing child.
    static TreeNode build(Integer[] values) {
        if (values.length == 0 || values[0] == null) {
            return null;
        }
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> parents = new ArrayDeque<>();
        parents.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode parent = parents.poll();
            if (values[i] != null) {
                parent.left = new TreeNode(values[i]);
                parents.add(parent.left);
            }
            i++;
            if (i < values.length && values[i] != null) {
                parent.right = new TreeNode(values[i]);
                parents.add(parent.right);
            }
            i++;
        }
        return root;
    }

    static void run(Integer... values) {
        System.out.println(Arrays.toString(values) + " -> " + maxDepth(build(values)));
    }

    public static void main(String[] args) {
        run(3, 9, 20, null, null, 15, 7);
        run(1, null, 2);
        run();
        run(5);
        run(1, 2, null, 3, null, 4);
        run(1, 2, 3, 4, 5, 6, 7);
    }
}

Running it prints:

Output
[3, 9, 20, null, null, 15, 7] -> 3
[1, null, 2] -> 2
[] -> 0
[5] -> 1
[1, 2, null, 3, null, 4] -> 4
[1, 2, 3, 4, 5, 6, 7] -> 3

Example 1 prints 3 and Example 2 prints 2, matching the picture and the depths worked out above. The empty input [] prints 0 straight from the first check, and the single node [5] prints 1, since it is a leaf.

Compare the last two lines. In [1, 2, null, 3, null, 4] each node has only a left child, so the four nodes form one chain and the depth is 4. The tree [1, 2, 3, 4, 5, 6, 7] has seven nodes but depth only 3, because each full row holds twice as many nodes as the row above it.

Complexity

Each call does one comparison and one addition, so the cost depends on how many calls there are and how many are open at once.

  • Time: O(n), because maxDepth runs once for each of the n nodes and once for each of the n + 1 empty children below them, 2n + 1 calls in all.
  • Space: O(h), because the open calls always lie on one path from the root, so at most h of them wait at once, where h is the tree's depth. That is n for a chain like [1, 2, null, 3, null, 4], and about log₂ n when every row is full.

The same depth computation, done at every node, is the core of Diameter of Binary Tree.