Count Univalue Subtrees
Given the root of a binary tree, return the number of uni-value subtrees.
A uni-value subtree means all nodes of the subtree have the same value.
Example 1:
Input: root = [5,1,5,5,5,null,5]
Output: 4
Example 2:
Input: root = []
Output: 0
Example 3:
Input: root = [5,5,5,5,5,null,5]
Output: 6
Constraints:
- The numbrt of the node in the tree will be in the range [0, 1000].
- -1000 <= Node.val <= 1000
Solution:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int count = 0;
public int countUnivalSubtrees(TreeNode root) {
isUni(root);
return count;
}
private boolean isUni(TreeNode root) {
if (root == null) return true;
if (root.left == null && root.right == null) {
count ++;
return true;
}
int val = root.val;
if (root.left == null) {
boolean right = isUni(root.right);
if (val == root.right.val && right) {
count ++;
return true;
}
} else if (root.right == null) {
boolean left = isUni(root.left);
if (val == root.left.val && left) {
count ++;
return true;
}
} else {
boolean left = isUni(root.left);
boolean right = isUni(root.right);
if (val == root.left.val && val == root.right.val && left && right) {
count ++;
return true;
}
}
return false;
}
}