Longest Univalue Path
Question (LC.687)
Given the root of a binary tree, find the length of the longest univalue path. An univalue path is a path between any two nodes where all the nodes have the same value. The length of the path is the number of edges.
Example
Input: [5,4,5,1,1,5]
Output: 2
Input: [1,4,5,4,4,5]
Output: 2
Input: [1,null,1,1,1,1,1,1]
Expected: 4
The last example is a good one. Same value nodes can only connect in one direction but not both.
Analysis
Divide and conquer is build for these path related problems. The return type needs to hold a couple info including the longest univalue path so far, the current univalue path, and the current value.
Code
Complexity
Time O(n)
Space O(n)
Last updated