*Count Univalue Subtrees

Given a binary tree, count the number of uni-value subtrees.

A Uni-value subtree means all nodes of the subtree have the same value.

For example:
Given binary tree,

              5
             / 
            1   5
           /    
          5   5   5

return 4.

public class Solution {
    public int count = 0;
    public int countUnivalSubtrees(TreeNode root) 
    {
        if(root==null)return 0;
        isUniValue(root);
        return count;
    }
    
    public boolean isUniValue(TreeNode node)
    {
        if(node==null) return true;
        boolean left = isUniValue(node.left);
        boolean right = isUniValue(node.right);
        if(left&&right)
        {
            if(node.left!=null&&node.left.val!=node.val)return false;
            if(node.right!=null&&node.right.val!=node.val)return false;
            count++;
            return true;
        }
        else return false;
    }
}

reference:https://leetcode.com/discuss/50357/my-concise-java-solution

原文地址:https://www.cnblogs.com/hygeia/p/5101107.html