Problem 609
Longest Univalue Path
Medium · 20 pts · Tree, Depth-First Search
Problem
Find the length of the longest path in a binary tree in which every node has the same value. The path may start and end anywhere and does not have to pass through the root. Its length is the number of edges, so a single node gives length 0. For each node, compute the longest same-value arm going down into each child; the best path through the node joins its two arms.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.
Output
Print the length (number of edges) of the longest univalue path.
Constraints
1 <= number of nodes <= 10000; -1000 <= value <= 1000
Example input
7 5 4 5 1 1 null 5
Example output
2
Explanation
In the tree 5 4 5 1 1 null 5, the path 5 - 5 - 5 runs from the root down its right side. It has 2 edges, and no longer path with equal values exists.