给定一个二叉树,统计该二叉树数值相同的子树个数。
同值子树是指该子树的所有节点都拥有相同的数值。
示例:
输入: root = [5,1,5,5,5,null,5]
5
/ \
1 5
/ \ \
5 5 5
输出: 4
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/count-univalue-subtrees 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
int count = 0;
public:
int countUnivalSubtrees(TreeNode* root) {
dfs(root);
return count;
}
bool dfs(TreeNode* root)
{
if(!root) return true;
bool l = dfs(root->left);//左子树都一样吗?
bool r = dfs(root->right);
if(!l || !r || (root->left && root->val != root->left->val)
||(root->right && root->val != root->right->val))
return false;//左右子树有不一样 or root值跟左右不相等
count++;
return true;
}
};
12 ms 16.3 MB