LeetCode刷题实战250:统计同值子树
共 3103字,需浏览 7分钟
·
2021-05-05 07:03
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.
示例
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 sum=0;
helper(root,sum);
return sum;
}
bool helper(TreeNode* node,int& sum){
if(node==0){
return true;
}
bool le=helper(node->left,sum),ri=helper(node->right,sum);
if(le and ri){
if(node->left and node->left->val!=node->val){
return false;
}
if(node->right and node->right->val!=node->val){
return false;
}
++sum;
return true;
}
return false;
}
};