文章目录
1. 题目2. 解题
1. 题目
给定一个二叉树,统计该二叉树数值相同的子树个数。
同值子树是指该子树的所有节点都拥有相同的数值。
示例:
输入
: root
= [5,1,5,5,5,null
,5]
5
/ \
1 5
/ \ \
5 5 5
输出
: 4
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/count-univalue-subtrees 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
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;
count
++;
return true;
}
};
12 ms 16.3 MB
我的博客地址 https://michael.blog.csdn.net/
长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!