Start learning free

LESSON 204 OF 321 · BINARY TREES

Maximum Depth of Binary Tree in Java: Recursion in O(n)

Practice O(n) Read the full explanation

You get the root of a binary tree. Return the depth of the tree.

The depth counts the nodes on the longest path from the root down to a leaf. A leaf is a node with no children. An empty tree has a depth of 0.

The trees below are listed level by level, top to bottom and left to right. A missing child is written as null.

 

Example 1:

      8
     / \
    4   -2
   /
  5
   \
    1

Input: root = [8,4,-2,5,null,null,null,null,1]
Output: 4
Explanation: The longest way down is 8 → 4 → 5 → 1.
It has 4 nodes.
The way to the other leaf, 8 → -2, has only 2 nodes.

Example 2:

Input: root = [6]
Output: 1
Explanation: The root is also the only leaf.

Example 3:

Input: root = []
Output: 0
Explanation: The tree is empty.

 

Constraints:

  • 0 to 10,000 nodes.
  • Each value is from -100 to 100.
  • The tree is at most 400 levels deep.

 

Follow up: Can you find the depth in O(n) time for n nodes? Look at each node just once.
STEP 1 OF 4
    Ctrl + Enter to check

    JAVA · BINARY TREES

    Maximum Depth Of Binary Tree in Java, explained

    Problem overview

    The method maxDepth receives the root of a binary tree and returns its maximum depth: the number of nodes on the longest path from the root down to a leaf. An empty tree, where root is null, has depth 0.

    The lesson provides the TreeNode class. It has an int val, a TreeNode left, a TreeNode right and a constructor TreeNode(int x); a missing child is null.

    For the tree [3,9,20,null,null,15,7], the paths 3, 20, 15 and 3, 20, 7 have three nodes each, while 3, 9 has two. The answer is 3. For [1,null,2] the only path is 1, 2, so the answer is 2.

    Approach: a tree is one deeper than its deeper subtree

    Every tree is a root with a left subtree and a right subtree, and both are themselves binary trees, possibly empty. The longest path from the root must go down through one of the two children, so:

    depth(tree) = 1 + max(depth(left subtree), depth(right subtree))

    The 1 counts the root. For an empty tree the depth is 0, which is where the recursion stops. A leaf then works out by itself: both children are empty, so its depth is 1 + max(0, 0) = 1.

    This visits every node exactly once, so the time is O(n) for n nodes. The statement's follow-up asks for exactly that.

    Step by step

    1. Write the base case. If root == null, return 0. This handles the empty tree and also ends the recursion when it steps below a leaf.
    2. Find the left depth. Call maxDepth(root.left) and store the result in an int named leftDepth. Trust the call to return the right answer for the smaller tree, whatever its shape.
    3. Find the right depth the same way, from root.right, into rightDepth. A missing child gives 0 thanks to the base case, so one-sided trees need no special handling.
    4. Combine. Return 1 + Math.max(leftDepth, rightDepth): the root, plus the longest path below it.

    The solution in Java

    class Solution {
        public int maxDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int leftDepth = maxDepth(root.left);
            int rightDepth = maxDepth(root.right);
            return 1 + Math.max(leftDepth, rightDepth);
        }
    }
    

    Java details worth knowing:

    • root == null is a reference check. A TreeNode variable holds either a reference to a node or null. Reading root.left when root is null throws a NullPointerException, which is why the base case comes first.
    • Each call has its own variables. leftDepth and rightDepth are local to one call, so the recursive calls don't interfere with each other.
    • Recursion uses the call stack. The recursion goes as deep as the tree. With a tree at most 400 levels deep, as here, that is no problem. A tree that is a chain of a hundred thousand nodes could overflow the stack with this approach, and an iterative level-by-level search would be needed.
    • Math.max takes two ints and returns the larger one.

    Complexity

    Time: O(n). Each node is visited once, and each visit does a constant amount of work. Each null child is also visited once and returns at once, which adds at most n + 1 extra calls.

    Space: O(h), where h is the height of the tree, for the call stack. That is about log n for a balanced tree and n for a chain.

    Edge cases and common mistakes

    • Empty tree. root = null returns 0.
    • Single node. A tree holding just 5 returns 1.
    • A chain. [1,null,2] returns 2, and [1,2,null,3] returns 3, because a missing child contributes 0.
    • Forgetting the 1 +. Without it, the method returns 0 for every tree.
    • Adding 1 only at leaves. Every node on the path counts, not just the last one, so the 1 + belongs in the general case, not only in a special case for leaves.
    • Counting edges instead of nodes. The lesson counts nodes, so a single node has depth 1, not 0.

    Testing

    These results come from running the solution on trees written in level order:

    • [3,9,20,null,null,15,7] gives 3.
    • [1,null,2] gives 2.
    • [] gives 0.
    • [5] gives 1.
    • [1,2,null,3] gives 3.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free