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