687. Longest Univalue Path
Problem
Return the number of edges in the longest path in which every node has the same value. The path need not pass through the root.
Example: [5,4,5,1,1,null,5] → 2; [1,4,5,4,4,null,5] → 2
Like the diameter: each node returns the longest downward arm with its own value. Arms from children count only if the child has the same value; update the global with left + right.
Complexity: O(n).
class Solution:
def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
best = 0
def arm(node):
nonlocal best
if not node:
return 0
l, r = arm(node.left), arm(node.right)
l = l + 1 if node.left and node.left.val == node.val else 0
r = r + 1 if node.right and node.right.val == node.val else 0
best = max(best, l + r)
return max(l, r)
arm(root)
return best
assert Solution().longestUnivaluePath(make_tree([5, 4, 5, 1, 1, None, 5])) == 2
assert Solution().longestUnivaluePath(make_tree([1, 4, 5, 4, 4, None, 5])) == 2
class Solution {
private int best = 0;
public int longestUnivaluePath(TreeNode root) {
arm(root);
return best;
}
private int arm(TreeNode n) {
if (n == null) return 0;
int l = arm(n.left), r = arm(n.right);
l = (n.left != null && n.left.val == n.val) ? l + 1 : 0;
r = (n.right != null && n.right.val == n.val) ? r + 1 : 0;
best = Math.max(best, l + r);
return Math.max(l, r);
}
}
func longestUnivaluePath(root *TreeNode) int {
best := 0
var arm func(*TreeNode) int // longest same-value path going down from node
arm = func(node *TreeNode) int {
if node == nil {
return 0
}
l, r := arm(node.Left), arm(node.Right)
if node.Left != nil && node.Left.Val == node.Val {
l++
} else {
l = 0
}
if node.Right != nil && node.Right.Val == node.Val {
r++
} else {
r = 0
}
best = max(best, l+r)
return max(l, r)
}
arm(root)
return best
}