Description
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
.
Code
class Solution {
public int countUnivalSubtrees(TreeNode root) {
if(root == null){
return 0;
}else{
int leftAndRight = countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right);
return isUnival(root) ? leftAndRight + 1 : leftAndRight;
}
}
boolean isUnival(TreeNode root){
if(root == null){
return true;
}else if(root.left != null && root.val != root.left.val || root.right != null && root.val != root.right.val){
return false;
}
else{
return isUnival(root.left) && isUnival(root.right);
}
}
}