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);
    }
}

posted @ 2019-07-21 10:17  小路不会迷路  阅读(114)  评论(0编辑  收藏  举报