451. Tree Depth

A botanist records the branching structure of a vine as a binary tree: every junction splits into at most a left and a right shoot, and the tree is handed to you as root. The botanist wants to know how tall the vine is, counted in junctions.

Return the number of nodes on the longest path that starts at root and walks downward through child links until it reaches a node with no further child. An empty tree (no junctions at all) has a depth of 0, and a tree consisting of a single node has a depth of 1.

Example 1

Input:
root = [7,2,9,null,4,null,1]
Output:
3
Explanation:

The longest downward paths are 7-2-4 and 7-9-1, each containing 3 nodes.

Example 2

Input:
root = [12,5,null,null,8]
Output:
3
Explanation:

Only one path exists below the root: 12, then 5, then 8, giving 3 nodes.

Constraints

0 ≤ number of nodes ≤ 105

-1000 ≤ node value ≤ 1000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(w)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…