[leetcode 250]Count Univalue Subtrees ------元素都相同的子树个数

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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值