Java version

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int longestUnivaluePath(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(straightUnivaluePath(root.left, root.val) + straightUnivaluePath(root.right, root.val),
Math.max(longestUnivaluePath(root.left), longestUnivaluePath(root.right)));
}
private int straightUnivaluePath(TreeNode node, int Univalue) {
if (node == null || node.val != Univalue) {
return 0;
}
return Math.max(straightUnivaluePath(node.left, Univalue), straightUnivaluePath(node.right, Univalue)) + 1;
}
}