Maximum Depth of Binary Tree
Problem (restated)
Given the root of a binary tree, return its maximum depth (number of nodes along the longest root-to-leaf path).
Intuition
Depth(node) = 1 + max(depth(left), depth(right)); empty node has depth 0.
Approaches
Recursive DFS
Tested onlyIdea. Base null→0; return 1+max of children.
Walkthrough. Balanced tree of height 3 → answer 3.
Trade-offs. BFS level-count is equivalent; DFS is shortest to write.
export class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
export function maxDepth(root: TreeNode | null): number {
if (!root) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
export class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
export function maxDepth(root: TreeNode | null): number {
if (!root) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
Template connection
Tree DFS returning aggregated info to parent.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?