Return the maximum depth of a binary tree: the number of nodes on the longest root-to-leaf path.
Push (node, depth) pairs onto a stack and track the largest depth seen.
1function maxDepth(root: TreeNode | null): number {2const stack: [TreeNode | null, number][] = [[root, 1]];3let best = 0;4while (stack.length) {5const [n, d] = stack.pop()!;6if (!n) continue;7best = Math.max(best, d);8stack.push([n.left, d + 1], [n.right, d + 1]);9}10return best;11}
Push (root, 1).
Space: play/pause · ←/→: step