Leetcode•May 27, 2025
Longest Univalue Path
Hazrat Ali
Leetcode
The length of the path between two nodes is represented by the number of edges between them.
Example 1:
Input: root = [5,4,5,1,1,null,5] Output: 2 Explanation: The shown image shows that the longest path of the same value (i.e. 5).
Example 2:
Input: root = [1,4,5,4,4,null,5] Output: 2 Explanation: The shown image shows that the longest path of the same value (i.e. 4).
Solution
/**
* @param {TreeNode} root
* @return {number}
*/
const longestUnivaluePath = root => {
const helper = node => {
if (!node) {
return 0;
}
let left = helper(node.left);
let right = helper(node.right);
if (node.left) {
left += node.left.val === node.val ? 1 : -left;
}
if (node.right) {
right += node.right.val === node.val ? 1 : -right;
}
max = Math.max(max, left + right);
return Math.max(left, right);
};
let max = 0;
helper(root);
return max;
};