Problem · Tree
Maximum Depth of an N-ary Tree
Learn this problemProblem statement
A rooted N-ary tree has nodes numbered from 0 through parent.length - 1. The single root has parent -1; every other entry parent[i] is the index of node i's parent.
Return the maximum depth of the tree, measured as the number of nodes on a path from the root to a deepest node. The root alone has depth 1.
Function
maximumNaryDepth(parent: int[]) → intExamples
Example 1
parent = [-1,0,0,1,1,3]return = 4The deepest path is 0 -> 1 -> 3 -> 5.
Example 2
parent = [-1]return = 1A one-node tree has depth one.
Example 3
parent = [4,4,0,0,-1,2]return = 4The path 4 -> 0 -> 2 -> 5 has four nodes; parent indices need not precede children.
Constraints
1 <= parent.length <= 100000.- Exactly one entry is
-1. - Every other entry is a valid different node index.
- The parent links form one rooted tree.