Question:
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
.
分析:
是求节点值都一样的所有子树个数,上面例子中元素都是5的子树有3个叶节点,和根节点的右子树。
如果有是子树,就必须有叶子节点,所以应该从叶子节点往上判断,但是节点没有父节点,无法往上判断,所以可以采用递归的方法从上往下调用判断。
以上面为例子:
计数器count初始为0
根节点为5,且有左右子树,所以分别判断左右子树是不是元素值都为5的子树个数count,如果是则count++,如果不是分别统计左子树的元素值一样的个数和右子树元素值一样的子树个数。
代码如下:
<span style="font-size:14px;">/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public:
int countUnivalSubtrees(TreeNode* root) {
unival(root);
return count;
}
bool unival(TreeNode *root) {
if(root == null)
return true;
if(root->left ==null && root->right == null) {
count++;
return true;
}
bool left = unival(root->left);
bool right = unival(root->right);
if(left && right && (root->left == null || root->left->val == root->val) && (root->right == null || root->right->val == root->val)) {
count++;
return true;
}
return false;
}
private:
int count = 0;
} </span>