/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int countUnivalSubtrees(TreeNode root) {
if (root == null) return 0;
int count = isUni(root) ? 1 : 0;
return count + countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right);
}
private boolean isUni(TreeNode root) {
boolean flag = true;
if (root.left != null) {
flag &= (root.val == root.left.val);
flag &= isUni(root.left);
}
if (root.right != null) {
flag &= (root.val == root.right.val);
flag &= isUni(root.right);
}
return flag;
}
}