LeetCode 250. 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. univalue subtree是指子树的每个节点的值都相等。例子中三个leaf node是子树且节点值相等,另外还有

          5
           \
            5

2. 需要dfs遍历,提取信息,做出判断。提取的信息是左右子树是否univalue或NULL,以及univalue的值是多少。如果root的值等于左右子树的univalue,则总的子树个数+1;否则传递信息表明当前不是univalue subtree

int countUnivalSubtrees(TreeNode* root) {
    //
    int res=0;
    int value=root->val;
    helper(root,res,value);
    return res;
}

bool helper(TreeNode* root,int&res,int&value){
    //
    if(!root) return true;
    int lvalue=root->val, rvalue=root->val;
    if(helper(root->left,res,lvalue)&&helper(root->right,res,rvalue)){
        if(lvalue==rvalue&&lvalue==root->value){
            res+=1;
            value=root->val;
            return true;    
        }
    }
    return false;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值