1029. Widest Family Span
Genealogists want to know how far apart the two most distantly connected people in a family tree are, where moving between a parent and a child counts as one step. You are given root, the top ancestor of a tree whose people may have any number of children. Return the largest number of steps on any path between two people. The path may go up and then down and does not have to pass through root.
An empty tree or a tree with a single person has span 0. The tree can hold 100000 people in one long line, so avoid recursion. Aim for O(n) time and O(n) space.
Example 1
- Input:
- root = [1,null,2,4,null,3]
- Output:
- 3
- Explanation:
The path 3, 2, 1, 4 uses three parent-child links, and no pair of people is farther apart.
Example 2
- Input:
- root = [1,null,2,null,3,4,5,null,6,null,7]
- Output:
- 4
- Explanation:
The longest path 6, 3, 2, 4, 7 has four links and avoids the root, which beats the three-link path down from the root.
Constraints
0 ≤ number of nodes n ≤ 105
-104 ≤ node value ≤ 104
A node may have any number of children; the tree is given as a rooted N-ary tree.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(n)