​LeetCode刷题实战250:统计同值子树

程序IT圈

共 3103字,需浏览 7分钟

 ·

2021-05-05 07:03

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 统计同值子树,我们先来看题面:
https://leetcode-cn.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.

给定一个二叉树,统计该二叉树数值相同的子树个数。
同值子树是指该子树的所有节点都拥有相同的数值。

示例


Input: root = [5,1,5,5,5,null,5]

              5
             /  \
            1   5
           /  \    \
          5   5   5

Output: 4


解题

节点node若是同值子树点,则其左右子树首先都是同值子树点,并且左右孩子的val与node的val相同。介于此,遍历node的时候,对左右子树dfs返回一个bool值,若都为真,再将三者的val进行对比,否则直接返回false。

class Solution {
public:
    int countUnivalSubtrees(TreeNode* root) {
        int sum=0;
        helper(root,sum);
        return sum;
    }
    bool helper(TreeNode* node,int& sum){
        if(node==0){
            return true;
        }
        bool le=helper(node->left,sum),ri=helper(node->right,sum);
        if(le and ri){
            if(node->left and node->left->val!=node->val){
                return false;
            }
            if(node->right and node->right->val!=node->val){
                return false;
            }
            ++sum;
            return true;
        }
        return false;
    }
};


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-240题汇总,希望对你有点帮助!

LeetCode刷题实战241:为运算表达式设计优先级

LeetCode刷题实战242:有效的字母异位词

LeetCode刷题实战243:最短单词距离

LeetCode刷题实战244:最短单词距离 II

LeetCode刷题实战245:最短单词距离 III

LeetCode刷题实战246:中心对称数

LeetCode刷题实战247:中心对称数II

LeetCode刷题实战248:中心对称数III

LeetCode刷题实战249:移位字符串分组


浏览 36
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报