THN Interview Prep

104. Maximum Depth of Binary Tree

At a Glance

  • Topic: trees
  • Pattern: Tree DFS
  • Difficulty: Easy
  • Companies: Amazon, Google, Meta, Apple, Bloomberg
  • Frequency: Very High
  • LeetCode: 104

Problem (one-liner)

Given the root of a binary tree, return the number of nodes along the longest path from the root down to a leaf (depth as edge count is often “levels − 1”; here LeetCode uses node count depth = root-to-leaf nodes).

Recognition Cues

  • "Maximum depth" / "height" of the tree
  • Longest path root to any leaf
  • Often first introductory recursion on trees

Diagram

At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.

Loading diagram…

Approaches

  • Brute forceO(n) time / O(n) space — collect all root-to-leaf paths and take max length (overkill).
  • BetterO(n) time / O(n) space — BFS level counting (same asymptotic, queue memory).
  • OptimalO(n) time / O(h) stack — DFS: depth = 1 + max(depth(left), depth(right)).

Optimal Solution

Go

package main

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func maxDepth(root *TreeNode) int {
	if root == nil {
		return 0
	}
	leftDepth := maxDepth(root.Left)
	rightDepth := maxDepth(root.Right)
	if leftDepth > rightDepth {
		return 1 + leftDepth
	}
	return 1 + rightDepth
}

JavaScript

class TreeNode {
	constructor(val = 0, left = null, right = null) {
		this.val = val;
		this.left = left;
		this.right = right;
	}
}

function maxDepth(root) {
	if (root === null) {
		return 0;
	}
	return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}

Walkthrough

Tree: 3 / 9,20 / null,null,15,7

nodeleft depthright depthreturn
9001
15001
7001
20112
3123

Invariant: subtree depth is correctly computed bottom-up; empty subtree contributes 0.

Edge Cases

  • root == null → depth 0
  • Single node → depth 1
  • Skewed list → depth n

Pitfalls

  • Off-by-one: returning depth without +1 for current level
  • Confusing edge-based height with node-based depth (stay consistent with problem definition)

Similar Problems

Variants

  • Minimum depth to leaf → different combine (careful: not just min of children if one side null).
  • Binary tree max width by level → BFS with level sizes.

Mind-Map Tags

#trees #dfs #height #recursion #divide-and-conquer-on-tree

Last updated on

Spotted something unclear or wrong on this page?

On this page