Logo for ammarahmed.ca
Easy
Oct 06, 2025
#binary-tree

104. Maximum Depth of Binary Tree

Problem

Given the root of a binary tree, return its maximum depth.

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

Example 1:

1Input: root = [3,9,20,null,null,15,7] 2Output: 3 3

Example 2:

1Input: root = [1,null,2] 2Output: 2 3

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
    • -100 <= Node.val <= 100

      Approach

      To solve this problem we can use a recursive approach using depth first search.

      We can write a separate recursive function that takes in a node and a depth parameter. If the node is nil, it returns the depth (base case). Otherwise, it returns the maximum of the recursive call on the right and left with the depth being incremented.

      In the main function, we check the base case if the root is null (return 0), otherwise, we return the max of our dfs function on the right and left nodes using a starting depth of 1.

      Complexity

      Time: O(n)

      Where n is the number of nodes

      Space: O(n)

      Recursive calls

      Solution

      1func dfs(root *TreeNode, depth int) int { 2 if root == nil { 3 return depth 4 } 5 6 return max(dfs(root.Right, depth + 1), dfs(root.Left, depth + 1)) 7} 8func maxDepth(root *TreeNode) int { 9 if root == nil { 10 return 0 11 } 12 return max(dfs(root.Right, 1), dfs(root.Left, 1)) 13} 14