Show problems as
Classic problem #104EasyTreeDepth-First SearchBreadth-First SearchBinary Tree

Maximum Depth of Binary Tree

Real-world version: Longest Run Through the Delta
Tracked in this browser only
Read Maximum Depth of Binary Tree on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A survey charts a river delta as junctions that split the flow downstream. Each junction sends water onward through at most two channels, one toward the west bank and one toward the east bank, and each junction records a signed bed grade in centimetres per kilometre.

The chart arrives as junctions, a listing that walks the delta one tier at a time starting at the source, with the west entry of a tier written before its east entry. Slot 0 holds the source junction. Every junction that appears in the listing claims the next two free slots, its west channel first and its east channel second. A slot holding null means no channel leaves in that direction, and such a slot claims no slots of its own. Trailing null slots may be left off, and an empty listing means nothing was charted.

A run begins at the source junction, follows channels downstream only, and halts at a junction that sends water nowhere. Report how many junctions sit on the longest run. When nothing was charted, report 0.

Examples

Example 1

Input
junctions = [12, -5, 40, null, 7]
Output
3

The source splits west into -5 and east into 40. The junction -5 sends water east into 7, so the longest run visits three junctions while the run through 40 visits only two.

Example 2

Input
junctions = []
Output
0

Nothing was charted, so no run exists and the answer is zero.

Example 3

Input
junctions = [-100]
Output
1

The source sends water nowhere, so the only run halts immediately after visiting one junction.

Constraints

  • The number of junctions in the chart is in the range [0, 10^4].
  • -100 <= grade of a junction <= 100
  • An empty listing means no junction was charted.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def delta_run_length(junctions: list[int | None]) -> int:
Java
public int deltaRunLength(Integer[] junctions)