Start learning free

LESSON 204 OF 314 · BINARY TREES

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

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

    JAVASCRIPT · BINARY TREES

    Maximum Depth Of Binary Tree in JavaScript, explained

    Problem overview

    maxDepth(root) 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 constructor: each node has a val, and its left and right start as null.

    For the tree written in level order as [3, 9, 20, null, null, 15, 7], the node 3 has children 9 and 20, and 20 has children 15 and 7. The paths 3 -> 20 -> 15 and 3 -> 20 -> 7 have 3 nodes each, while 3 -> 9 has 2, so the answer is 3. The tree [1, null, 2] has depth 2, and an empty tree has depth 0.

    Approach: a tree is one deeper than its deeper subtree

    A path from the root goes through either the left child or the right child. So the depth of a tree is one (for the root itself) plus the depth of whichever subtree is deeper:

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

    Each subtree is a smaller tree of the same kind, so the same rule applies to it. That is recursion. It needs a base case where the answer is known without any further calls: an empty tree has depth 0. A missing child is null, so the base case also handles leaves, whose two children are both empty and give 1 + max(0, 0) = 1.

    The follow-up asks for O(n) time with each of the n nodes visited once. This recursion does exactly that: every node is reached by one call from its parent, and the base case ends the calls below the leaves.

    Step by step

    1. Write the base case. If root is null, written as !root, return 0. This ends the recursion when a call steps past a leaf.
    2. Get the left depth. Call this.maxDepth(root.left) and keep the result in leftDepth. Trust the call to return the right depth for the smaller tree, whatever its shape.
    3. Get the right depth the same way, with root.right. A missing child gives 0.
    4. Combine them. Return 1 + Math.max(leftDepth, rightDepth): the root, plus the longest path below it.

    The solution in JavaScript

    class Solution {
        maxDepth(root) {
            if (!root) {
                return 0;
            }
            let leftDepth = this.maxDepth(root.left);
            let rightDepth = this.maxDepth(root.right);
            return 1 + Math.max(leftDepth, rightDepth);
        }
    }
    

    The JavaScript details worth a closer look:

    • this.maxDepth. Inside a class method, a recursive call to another method of the same class needs this. in front. Writing just maxDepth(...) looks for a variable of that name and fails with a ReferenceError.
    • !root. A null value is falsy and a node object is truthy, so !root is true exactly for an empty tree. It also covers undefined, though the tree's missing children are always null.
    • Math.max. It returns the larger of its arguments, here the deeper of the two subtrees.
    • The call stack. Each recursive call waits on the stack for its children. The depth of the recursion equals the depth of the tree, which the statement limits to 400 levels, far from the limit of a JavaScript engine.

    Complexity

    Time: O(n). The function is called once for every node, plus once for each missing child. That is at most 2n + 1 calls, and each does a constant amount of work.

    Space: O(h), where h is the height of the tree. The recursion keeps one call on the stack for each level it is currently inside. That is about log n for a balanced tree and n for a chain, where every node has only one child.

    Edge cases and common mistakes

    • Empty tree. maxDepth(null) returns 0 without touching root.left, which would throw on null.
    • A single node. The tree [5] returns 1: both children give 0, and 1 + max(0, 0) is 1.
    • A chain. The tree [1, 2, null, 3, null, 4] goes down the left side four levels and returns 4. A tree where every node has just one child works the same way, as does a chain of the maximum 400 levels.
    • Counting edges instead of nodes. The depth here counts nodes. For the first example that means 3, not 2. Returning 0 for a leaf instead of 1 gives edge counts.
    • Forgetting the 1 +. Without it the function returns 0 for every tree.
    • Adding instead of taking the maximum. leftDepth + rightDepth counts both sides, but a path goes down only one of them.
    • Only checking one child. A node with only a right child, like the root in [1, null, 2], must still count the right subtree. The base case handles the missing left child, so no special case is needed.

    Testing

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