Longest univalue path
Standard · Write code · about 18 min
root is a binary tree. Find the longest path between any two nodes in which every node holds the same value. The path may or may not pass through the root.
Return its length counted in edges.
Example 1
Input:
[[5,4,5,1,1,null,5]]
Output:
2
The three 5s, root, right child and its right child, form a path of 2 edges.
Example 2
Input:
[[1,4,5,4,4,null,5]]
Output:
2
The 4 and its two 4 children form a path of 2 edges.
Constraints
- 0 ≤ number of nodes ≤ 10,000
- -1000 ≤ node.val ≤ 1000
Learn the idea first: Tree DP, a visual lesson.
More Tree DP problems
- Fill the two numbers Warm-up
- House robber III Standard
- Binary tree cameras Standard