Example 1 · empty
- Arguments
- children
[]
- Expected return
0
Test data
- Input
{"children":[]}- Expected output
0
func TreeDepth(children [][2]int) intExamples use {"children": [[left, right], ...]}.
The runner calls your functions directly; you do not need to parse JSON.
[]
0
{"children":[]}0
[
[
-1,
-1
]
]1
{"children":[[-1,-1]]}1
[
[
1,
2
],
[
-1,
-1
],
[
-1,
-1
]
]2
{"children":[[1,2],[-1,-1],[-1,-1]]}2
[
[
-1,
1
],
[
-1,
2
],
[
-1,
3
],
[
-1,
-1
]
]4
{"children":[[-1,1],[-1,2],[-1,3],[-1,-1]]}4
Every root-to-leaf path through a node continues through one of its children. Taking the larger child depth selects the longest continuation, and adding one counts the current node. Applying this relation from the leaves back to root counts nodes rather than edges.
O(n) time because each node is visited once. Recursive depth-first traversal uses O(h) auxiliary stack space for tree height h, O(n) in a chain; returned output is one integer.
Checking execution availability…
View inputs and expected outputs. Examples do not run your code.