Start learning free

LESSON 204 OF 314 · BINARY TREES

Maximum Depth of Binary Tree in TypeScript: 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

    TYPESCRIPT · BINARY TREES

    Maximum Depth Of Binary Tree in TypeScript, 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, with a val and two children, left and right, each a TreeNode or 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 longest paths, 3 → 20 → 15 and 3 → 20 → 7, have 3 nodes, while 3 → 9 has only 2. The answer is 3.

    Approach

    A tree is built from smaller trees: each child of a node is the root of a subtree. That gives a way to state the answer in terms of itself:

    depth(tree) = 1 + the larger of depth(left subtree) and depth(right subtree)

    The 1 counts the root, and the larger depth is the longest path below it. An empty tree has depth 0, which ends the recursion. This is a depth-first walk: each node is visited once, so the time is O(n) for n nodes.

    Step by step

    1. Base case. If root is null (the test !root is true), return 0. This also stops the recursion when it steps past a leaf, because a leaf's missing children are null.
    2. Depth of the left subtree. Call this.maxDepth(root.left) and store it in leftDepth. Trust the call to return the right depth for the smaller tree, however it is shaped.
    3. Depth of the right subtree. Do the same with root.right. A missing child gives 0 thanks to the base case.
    4. Combine them. Return 1 + Math.max(leftDepth, rightDepth): the root, plus the longest path through its deeper side.

    The solution in TypeScript

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

    Details for TypeScript:

    • this.maxDepth. Inside a class, a method calls itself through this. Writing maxDepth(...) alone would look for a separate function with that name.
    • !root. null is falsy, and an object is truthy, so !root is true exactly for an empty tree. A TreeNode is always an object, even when its val is 0.
    • The parameter type TreeNode | null tells the compiler that the tree may be empty. It is erased when the code is compiled to JavaScript, so nothing about it is checked while the program runs.
    • Math.max takes any number of arguments and returns the largest.

    Walking through an example

    On [3,9,20,null,null,15,7], the calls go down the tree and answer on the way back. Each indented line is a call one level deeper:

    node 3
      node 9
        null -> 0
        null -> 0
      node 9 -> 1 + max(0, 0) = 1
      node 20
        node 15
          null -> 0
          null -> 0
        node 15 -> 1 + max(0, 0) = 1
        node 7
          null -> 0
          null -> 0
        node 7 -> 1 + max(0, 0) = 1
      node 20 -> 1 + max(1, 1) = 2
    node 3 -> 1 + max(1, 2) = 3
    

    Complexity

    Time: O(n). Each node is visited once and does a constant amount of work. Space: O(h), where h is the height of the tree, for the recursion's call stack: one call per level of the path being followed. For a balanced tree h is about log n; for a tree that is a single chain it is n. The lesson's trees are at most 400 levels deep, which a JavaScript call stack handles easily. A chain of 400 nodes returns 400. A much deeper chain, such as 10,000 nodes, is a different matter: it overflows Node's default call stack with a RangeError.

    Edge cases and common mistakes

    • Empty tree. root = [] arrives as null and the answer is 0.
    • A single node. Both children are null, so the answer is 1 + max(0, 0) = 1.
    • A one-sided tree. For [1,null,2] the left depth is 0 and the right depth is 1, so the answer is 2. Taking Math.min instead of Math.max would wrongly give 1.
    • Forgetting the 1 +. Without it the function always returns 0.
    • Counting edges instead of nodes. The depth here counts nodes, so a single node has depth 1, not 0.

    Testing

    Tree (level order)Result
    [3,9,20,null,null,15,7]3
    [1,null,2]2
    []0
    [5]1
    [1,2,null,3]3
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free