/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
const longestUnivaluePath = function (root) {
let res = 0
const calculate = function (root) {
if (root == null) return 0
const leftCount = calculate(root.left)
const rightCount = calculate(root.right)
let left = 0,
right = 0
if (root.left != null && root.left.val == root.val) {
left = leftCount + 1
}
if (root.right != null && root.right.val == root.val) {
right = rightCount + 1
}
res = Math.max(res, left + right)
return Math.max(left, right)
}
calculate(root)
return res
};