题目链接: https://leetcode.com/problems/count-univalue-subtrees/
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
.
思路: 题意是说如果一个结点的左子树和右子树的值都相等, 那么就计数+1. 因此我们只需要一个递归的判定一个结点出发,是否其所有结点都相等即可.叶子结点也算是一个结果.
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool DFS(TreeNode* root, int pre, int& ans)
{
if(!root) return true;
bool flag1 = DFS(root->left, root->val, ans);
bool flag2 = DFS(root->right, root->val, ans);
if(flag1 && flag2) ans++;
return (root->val == pre) && flag1 && flag2;
}
int countUnivalSubtrees(TreeNode* root) {
if(!root) return 0;
int ans = 0;
DFS(root, root->val, ans);
return ans;
}
};