Example 1
- Input
- root = [3,9,20,null,null,15,7]
- Output
- 3
The path 3 to 20 to 15 holds 3 nodes, which beats the 2-node path through 9.
Given the root of a binary tree, return the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0.
Given the root of a binary tree, return its maximum depth.
The maximum depth is the number of nodes along the longest downward path from the root to any leaf. An empty tree has depth 0, and a single node has depth 1.
The path 3 to 20 to 15 holds 3 nodes, which beats the 2-node path through 9.
The missing left child does not stop the path through the right child: 1 to 2 contains two nodes. A minimum of the child depths would incorrectly discard this path.
Empty edge case: there is no root and no root-to-leaf path, so zero nodes contribute to the depth.
Duplicate negative values denote distinct nodes. The right subtree continues down a left-child chain, giving the four-node path with values 0, -1, -1, -1. Values and signs do not determine depth.
Depth counts nodes on one downward path, not edges or values. In Example 1, the path from 3 through 20 to 15 has three nodes, while the path to 9 has two. Count nonempty horizontal levels, or compute each child subtree depth and add one to the larger answer. An empty child contributes zero, making a leaf contribute one; taking a maximum chooses one path rather than combining both branches.
Reveal Level Count With BFS: intuition, complexity, and code
0; a singleton returns 1, including zero or negative values.shift() may move remaining array entries and make wide-tree traversal quadratic.Height is a post-order summary: empty contributes zero, and each parent adds itself to the larger child answer. Breadth-first level counting computes the same quantity outward from the root. Choose between width-dependent frontier storage and height-dependent recursive storage according to tree shape and runtime stack capacity.