题目描述:
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.
Example :
Input: root = [5,1,5,5,5,null,5]
5
/ \
1 5
/ \ \
5 5 5
Output: 4
class Solution {
public:
int countUnivalSubtrees(TreeNode* root) {
int count=0;
isUnivalue(root,count);
return count;
}
bool isUnivalue(TreeNode* root, int& count)
{
if(root==NULL) return true; // 当节点为空时,返回true,但是不能让count增加
bool left=isUnivalue(root->left,count);
bool right=isUnivalue(root->right,count);
if(left&&right)
{
if(root->left!=NULL&&root->val!=root->left->val) return false;
else if(root->right!=NULL&&root->val!=root->right->val) return false;
else
{
count++;
return true;
}
}
else return false;
}
};