Tensorum
LeetCode 104 · DFS Basics

Maximum Depth of Binary Tree

LeetCode 104 · Easy · solution, intuition & step-by-step walkthrough

depth = 1 + max(depth(left), depth(right)).

EasyTreeDepth-First SearchBreadth-First SearchBinary Tree
0 msruntime · beats 100%
20.2 MBmemory · beats 100%
1approach
14accepted runs · last 16 Mar 2026

This is how I solved Maximum Depth of Binary Tree (LeetCode 104), an easy problem from the DFS Basics pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

A tree's depth is one more than the deeper of its two subtrees; an empty tree has depth 0.

Approach

  1. 1

    Empty → 0.

  2. 2

    Recurse on both children.

  3. 3

    Return 1 + the larger.

How I solved it

Post-order recursionPythonO(n) time · O(h) space
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        def dfs(node):
            if node==None:
                return 0
            left = max(0,dfs(node.left))
            right = max(0,dfs(node.right))
            return 1+max(left,right)
        return dfs(root)
Loading the step-through…

Maximum Depth of Binary Tree — FAQ

What is the intuition behind Maximum Depth of Binary Tree?

A tree's depth is one more than the deeper of its two subtrees; an empty tree has depth 0.

How do you solve Maximum Depth of Binary Tree (LeetCode 104)?

1. Empty → 0. 2. Recurse on both children. 3. Return 1 + the larger.

What is the time and space complexity of Maximum Depth of Binary Tree?

Time: O(n). Space: O(h). (Accepted approach: Post-order recursion.)

What are common mistakes in Maximum Depth of Binary Tree?

BFS by levels gives the same answer iteratively.