Logo for ammarahmed.ca
Easy
Dec 23, 2025
#binary-tree
#dfs

104. Maximum Depth of Binary Tree

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

Example 2:

1Input: root = [1,null,2] 2Output: 2
  • The number of nodes in the tree is in the range [0, 104].
    • -100 <= Node.val <= 100

      Constraints:

      Notes

      Intuition

      The maximum depth of a binary tree is the longest path from root to any leaf. At each node, the depth is one plus the maximum depth of its subtrees.

      Implementation

      Create a recursive DFS function that takes the current node and accumulated depth. When the node is None, we've gone past a leaf, so return the current depth. Otherwise, recurse on both children with depth + 1 and return the maximum of the two results.

      Edge-cases

      An empty tree (null root) returns 0, which the base case handles naturally.

      • Time: O(n) — visit every node
        • Space: O(n) — worst case recursion depth for a skewed tree; O(log n) for balanced

          Complexity

          Solution

          1from typing import Optional 2from lcutils import TreeNode 3 4# Definition for a binary tree node. 5# class TreeNode: 6# def __init__(self, val=0, left=None, right=None): 7# self.val = val 8# self.left = left 9# self.right = right 10class Solution: 11 def dfs(self, root: Optional[TreeNode], depth: int) -> int: 12 if not root: 13 return depth 14 return max(self.dfs(root.left, depth + 1), self.dfs(root.right, depth + 1)) 15 def maxDepth(self, root: Optional[TreeNode]) -> int: 16 return self.dfs(root, 0) 17 18 19 20 21if __name__ == "__main__": 22 # Include one-off tests here or debugging logic that can be run by running this file 23 # e.g. print(solution.two_sum([1, 2, 3, 4], 3)) 24 solution = Solution() 25