Skip to main content

Longest Univalue Path

Problem statement

Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.

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,5]Output: 2

Example 2:

Input: root = [1,4,5,4,4,5]Output: 2

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -1000 <= Node.val <= 1000
  • The depth of the tree will not exceed 1000.

My solution

/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var longestUnivaluePath = function(root) {
let counts = [];


const recursiveFunction = (node) => {
if (node === null) {
return 0;
}

const longestLeftPath = recursiveFunction(node.left);
const longestRightPath = recursiveFunction(node.right);

let leftCount = 0;
let rightCount = 0;

if (node.left !== null && node.val === node.left.val) {
leftCount = longestLeftPath + 1;
}

if (node.right !==null && node.val === node.right.val) {
rightCount = longestRightPath + 1;
}

counts.push(leftCount + rightCount);

return Math.max(leftCount, rightCount);
};

recursiveFunction(root);

return counts.length === 0 ? 0 : Math.max(...counts);
};