Beyond Big O

Tree depth

Tree depth

Easy

Your task

  • Find the longest path from the root of a binary tree to a leaf.
  • Return the number of nodes on that path.
  • An empty tree has depth 0; a single node has depth 1.

Required API

  • TreeDepth
    func TreeDepth(children [][2]int) int

Behavior

  • The tree is an array of child pairs.
  • Row i contains [left, right], the indices of node i’s children.
  • A value of -1 means there is no child.
  • The root is node 0.
  • Leave the input unchanged and keep separate calls independent.
  • Aim for O(n) time using only the standard library.

Constraints

  • The input is a valid rooted binary tree with 0–200 nodes.
  • Every node other than the root has exactly one parent, and all nodes are reachable from the root.
Notes and example notation

Examples use {"children": [[left, right], ...]}.

Examples

The runner calls your functions directly; you do not need to parse JSON.

Example 1 · empty

Arguments
children
[]
Expected return
0
Test data
Input
{"children":[]}
Expected output
0

Example 2 · single node

Arguments
children
[
  [
    -1,
    -1
  ]
]
Expected return
1
Test data
Input
{"children":[[-1,-1]]}
Expected output
1

Example 3 · balanced

Arguments
children
[
  [
    1,
    2
  ],
  [
    -1,
    -1
  ],
  [
    -1,
    -1
  ]
]
Expected return
2
Test data
Input
{"children":[[1,2],[-1,-1],[-1,-1]]}
Expected output
2

Example 4 · right chain

Arguments
children
[
  [
    -1,
    1
  ],
  [
    -1,
    2
  ],
  [
    -1,
    3
  ],
  [
    -1,
    -1
  ]
]
Expected return
4
Test data
Input
{"children":[[-1,1],[-1,2],[-1,3],[-1,-1]]}
Expected output
4
Editor options
Typing preferences

Saved in this browser.

Restoring local drafts…