Algorithm

Maximum Depth of Binary Tree

Trees Pattern

Maximum Depth of Binary Tree

Given the root of a binary tree, return its maximum depth: the number of nodes along the longest downward path from the root to any leaf. A leaf is a node with no children. By this counting, a single node has depth 1, and an empty tree has depth 0.

CONSTRAINTS
  • The number of nodes in the tree is in the range [0, 10⁴]
  • -100 <= Node.val <= 100
  • Depth is measured in nodes, not edges
  • The tree may be a single chain, so the depth can equal the node count
EXAMPLE 1
Input: root = [3,9,20,null,null,15,7]
Output: 3
The longest root-to-leaf path is 3, 20, 15 (or equally 3, 20, 7) and contains 3 nodes. The path 3, 9 is shorter, and a shorter path never lowers the answer — only the deepest one counts.
EXAMPLE 2
Input: root = [1,null,2]
Output: 2
1 has no left child at all, so the only path down is 1 then 2. The missing side contributes nothing rather than counting as a level.
EXAMPLE 3
Input: root = [1,2,3,4,null,null,null,5]
Output: 4
The path 1, 2, 4, 5 has 4 nodes while 1, 3 has only 2. The tree is lopsided, which is allowed — nothing requires the two sides to be similar in size.
EXAMPLE 4
Input: root = []
Output: 0
There are no nodes on any path, so the count is zero. This is the value that makes the counting consistent, not a special error case.
Is depth counted in nodes or in edges?
Nodes here, so a lone node has depth 1 and an empty tree has depth 0. Always confirm this — the edge convention gives answers exactly one smaller, and the off-by-one is the most common way to fail this problem.
Does the path have to end at a leaf?
Effectively yes: stopping early can only produce a shorter count, so the longest path always runs all the way down to a leaf.
Can the tree be badly unbalanced?
Yes. Nothing here promises balance, so with 10⁴ nodes in one chain the recursion could go 10⁴ frames deep — worth raising if the interviewer cares about stack limits.
Do negative values affect the depth?
No. Depth is purely structural; the values are never read. That distinguishes it from Path Sum, where the values are the whole point.

How tall is a tree? Count the nodes on the longest path from the top down to the lowest leaf. That count is what we want.

text
        3
       / \
      9   20        depth = number of NODES on the longest top-to-bottom path
          / \
        15   7

  path 3-9      has 2 nodes
  path 3-20-15  has 3 nodes   <-- longest   ->  depth = 3

Read the picture: two ways lead down from the root. The short way (3, 9) touches 2 nodes; the long way (3, 20, 15) touches 3. Depth is the longest one, so the answer is 3. Only the deepest branch matters — the shorter side never lowers it.

A node can't measure itself alone

Imagine you are standing on one node and someone asks, "how tall are you?" You honestly can't answer on your own — your height depends on everything hanging below you, and you can't see all of that from where you stand.

So you do the obvious thing: you turn to your two children and ask each of them the very same question. "How tall are you?" Each child goes off, asks their kids, and eventually comes back with a number.

Now you can answer. You look at the taller of the two numbers, add 1 for yourself, and that's your height. You hand that number up to whoever asked you.

And notice when you finally did your bit of work — the "add 1" — it was after both kids reported back, on the way up, not on the way down. You couldn't have done it earlier; there was nothing to add until the numbers arrived. Doing a node's work after visiting its children like this has a name: post-order. You didn't choose it, the problem forced it — your height depends on what's below, so you must hear from below first.

Where it bottoms out

This asking-your-kids keeps going down until it hits empty space — a missing child. Empty ground is 0 nodes tall. That's the floor the whole thing stands on, and it's the only case we answer without asking anyone.

So a leaf (both children empty) sees 0 and 0, takes the bigger (still 0), adds 1, and reports height 1. Exactly right — a lone node is one node tall.

The code
python
def maxDepth(node):
    if node is None:
        return 0                    # empty ground is 0 tall
    left  = maxDepth(node.left)     # ask left kid how tall it is
    right = maxDepth(node.right)
    return 1 + max(left, right)     # tallest kid, plus me

One thing to hold onto: it's max, not left + right. A path runs down one side of you — you can't walk down both at the same time — so you keep the taller side and drop the shorter.

Watch it climb back up

Tree with root 3, children 9 and 20; under 20 hang leaves 15 and 7. The number in (brackets) is the height each node reports upward to its parent:

text
        3 (3)          <- 1 + max(1, 2) = 3   the answer
       /    \
   9 (1)    20 (2)     <- 1 + max(1, 1) = 2
            /    \
       15 (1)   7 (1)  <- leaves: 1 + max(0, 0) = 1

Bottom-up: the leaves (15, 7, 9) each see empty ground below them (0) and report 1. Node 20 hears 1 and 1, keeps the bigger, adds itself: 2. The root hears 1 (from 9) and 2 (from 20), takes 2, adds itself: 3.

- Leaf 9 asks its (empty) kids → gets 0 and 0 → reports 1 + 0 = 1.
- Leaves 15 and 7 do the same → each reports 1.
- Node 20 hears 1 and 1 back → reports 1 + max(1, 1) = 2.
- Root 3 hears 1 (from 9) and 2 (from 20) → reports 1 + max(1, 2) = 3.

Answer 3. Each node is asked once and answers once, so nothing is redone — O(N) time, O(H) stack.

The habit worth keeping

Every node here did the same little dance: I can't answer alone, so I ask below me, wait for the numbers to come back, then combine them and pass mine up. That "ask the children, then combine on the way back up" move is post-order, and it's the heart of almost every tree problem — only the combine step (1 + max here) changes from one problem to the next.

The only time you'd flip it around is when a node needs something from above instead — a value carried down from the root — and then you do your work on the way down, before asking the kids. That's pre-order, and it's the story for a different day. Quick compass: need it from your children → post-order; carry it down from your parent → pre-order.

Interactive Strategy Visualization

Maximum Depth Audit

Recursive Height Reporting

1235
Explore Root (1). Moving Left.
Recursive Buffer
Result for Current Call
?

Height of a node is 1 + maximum of its children's heights.

"Base Case: Return 0 when node is null."

Strategy

Post-order DFS is natural here: we cannot know a parent's height until we know its children's.

"H = max(L, R) + 1"

O(N) Time · O(H) Space Post-order Recursion
O(N) Time · O(W) Space Level-by-Level BFS