1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {TreeNode} root
    11. * @return {number}
    12. */
    13. const longestUnivaluePath = function (root) {
    14. let res = 0
    15. const calculate = function (root) {
    16. if (root == null) return 0
    17. const leftCount = calculate(root.left)
    18. const rightCount = calculate(root.right)
    19. let left = 0,
    20. right = 0
    21. if (root.left != null && root.left.val == root.val) {
    22. left = leftCount + 1
    23. }
    24. if (root.right != null && root.right.val == root.val) {
    25. right = rightCount + 1
    26. }
    27. res = Math.max(res, left + right)
    28. return Math.max(left, right)
    29. }
    30. calculate(root)
    31. return res
    32. };