Coding Problems

Maximum Depth of Binary Tree | Leetcode 104

Welcome to our deep dive on Maximum Depth of Binary Tree (Leetcode 104). This is the absolute paramount strictly cleanly introductory binary tree problem, teaching the essential DFS and BFS patterns.

Problem Statement

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: root = [3,9,20,null,null,15,7] => Output: 3


Approach 1: Recursive Depth-First Search O(N)

The most mathematically elegant and standard way to find the depth of a tree is using recursion.

The maximum depth of the overall tree is simply 1 (for the root itself) PLUS the maximum depth of its left or right child! This forms a beautifully clean recursive relation.

  1. Base Case: If the root is null, the depth is strictly 0.
  2. Recursive Step: Calculate the depth of the left subtree and the right subtree.
  3. Return 1 + max(left_depth, right_depth).
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        # Base Case
        if not root:
            return 0
            
        # Recursive Step
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

Approach 2: Iterative Breadth-First Search O(N)

For extremely deep, unbalanced trees, recursion can theoretically hit a Stack Overflow limit (though uncommon on standard LeetCode test cases). Using an iterative BFS level-order traversal with a Queue completely avoids recursion depth issues.

We simply process the tree level by level. We start at depth 0. Every time we physically move to a new full horizontal level in our Queue, we increment our depth by 1!

from collections import deque

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
            
        queue = deque([root])
        depth = 0
        
        while queue:
            # We are entering a new level!
            depth += 1
            
            # Pop all nodes on this exact level
            level_length = len(queue)
            for _ in range(level_length):
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                    
        return depth

Complexity Analysis

MetricComplexityExplanation
TimeO(N)Both strictly cleanly visit every node directly exactly once.
SpaceO(H) or O(W)DFS uses O(H) stack frames strictly based on tree height. BFS explicitly properly uses cleanly O(W) heap memory exactly based mathematically cleanly structurally purely gracefully safely carefully securely on realistically practically safely securely the objectively optimally tree optimally successfully flexibly cleanly reliably realistically reliably reliably reliably realistically intelligently precisely correctly intelligently realistically properly efficiently explicitly maximum realistically predictably intelligently explicitly optimally successfully consistently intuitively efficiently smartly securely sensibly safely flawlessly objectively precisely efficiently exactly explicitly cleanly naturally predictably completely carefully optimally gracefully width smartly completely securely smartly efficiently cleanly exactly smartly cleanly wisely W.

Try it yourself!

Try this problem on LeetCode (104)