**Input:** root = [5,1,5,5,5,null,5]
**Output:** 4
**Input:** root = []
**Output:** 0
**Input:** root = [5,5,5,5,5,null,5]
**Output:** 6
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int cnt;
public int countUnivalSubtrees(TreeNode root) {
cnt = 0;
helper(root);
return cnt;
}
private boolean helper(TreeNode root) {
// exit
if (root == null) return true;
if (root.left == null && root.right == null) {
cnt++;
return true;
}
// handle
// subtree is uni-value?
boolean left = helper(root.left);
boolean right = helper(root.right);
if (!left || !right) {
return false;
}
// root value equals children value?
int lval = root.left != null ? root.left.val : root.val;
int rval = root.right != null ? root.right.val : root.val;
if (root.val == lval && root.val == rval) {
cnt++;
return true;
}
// unequal, return false
return false;
}
}