Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Maximum Depth of Binary Tree

LeetCode #104Easy
Depth = 1 + max(left, right)

Given the root of a binary tree, return its maximum depth: the number of nodes along the longest path from the root down to the farthest leaf.

Asked atAmazonGoogleLinkedIn
step 1 / 18
binary tree
9
3
15
20
7
call stack ↓
(returned)
Recursive DFS (post-order)
1depth(node):
2 push frame
3 if node is null: return 0 // base case
4 L = depth(node.left)
5 R = depth(node.right)
6 return 1 + max(L, R) // combine
state
  • goallongest root→leaf

line 1Maximum depth = the longest root-to-leaf chain. DFS expresses this in one line: a node's depth is 1 + the deeper of its two children. We let recursion (and the call stack) do the bookkeeping — watch the values bubble UP from the leaves.