<AI/>
enru
All posts

Maximum depth of binary tree

LeetCode 104: Find the maximum depth of a binary tree using a simple recursive depth-first search.

Difficulty
Easy
Published
Topics
#tree#binary tree
Open on LeetCode

Problem Description

Find the maximum depth of a binary tree.

The maximum depth of a binary tree is the number of nodes along the longest path from the root node down to the farthest leaf node.

Constraints

  • The number of nodes in the tree is from 0 to 10000
  • Each node value is in the range from -100 to 100

Examples

Input:

depth 1 depth 2 depth 3 3 9 20 15 7


Answer: 3

Solution

All we need is a simple depth-first search (DFS).

We implement a helper recursive function dfs that takes two arguments:

  • the current tree node node
  • the current depth level

The function returns the maximum depth of the branch.

If dfs receives an empty node, it means we've gone below the last leaf of this branch, i.e. we've reached its end. In this case we return level, since it represents the current depth of the branch.

If the node exists, we need to find which of its child branches is deeper. To do that, we recursively search the left and right child branches, passing the depth increased by 1. Having received two numbers for the left and right branches, we pick the larger one and return it.

Finally, the main maxDepth function calls our DFS with an initial depth of 0.

typescript
export type TreeNode = {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
};
 
export function maxDepth(root: TreeNode | null): number {
  return dfs(root, 0);
}
 
function dfs(node: TreeNode | null, level: number): number {
  if (!node) {
    return level;
  }
 
  const leftDepth = dfs(node.left, level + 1);
  const rightDepth = dfs(node.right, level + 1);
 
  return Math.max(leftDepth, rightDepth);
}

Complexity Analysis

Time Complexity

O(n), since we need to visit every node of the tree.

Space Complexity

Although we don't explicitly allocate memory that depends on the input size, the problem is solved with recursion. This means the result of the very first call isn't available until the results of all nested recursive calls are. So in the worst case we keep n frames on the call stack. Therefore, the space complexity is O(n).