力扣-贪心-968 监控二叉树

思路

用true和false作为放置了摄像头,会有局限,就是没法判断以下情况

所以要用数字代表三种状态

  • 2:有覆盖
  • 1:有摄像头
  • 0:无覆盖

两个节点都被覆盖时,要返回0

两个节点有一个无覆盖就要返回1

两个节点有一个有摄像头,返回覆盖即可

代码

cpp 复制代码
class Solution {
public:
    int res = 0;
    int mindTracing(TreeNode* root){
        if(root == nullptr) return 2;
        int left = mindTracing(root->left);
        int right = mindTracing(root->right);

        if(left == 2 && right == 2){
           return 0;
        }
        if(left == 0 || right == 0){
            res++;
            return 1;
        }
        if(left == 1 || right == 1){
            return 2;
        }
        return -1;
    }
    int minCameraCover(TreeNode* root) {
        if(root->right == nullptr && root->left == nullptr) return 1;
        if(mindTracing(root) == 0){
            res++;
        }
        return res;
    }   
};
相关推荐
Christo31 小时前
AAAI-2024《Multi-Class Support Vector Machine with Maximizing Minimum Margin》
人工智能·算法·机器学习·支持向量机·数据挖掘
元亓亓亓2 小时前
LeetCode热题100--79. 单词搜索
算法·leetcode·职场和发展
司铭鸿3 小时前
化学式解析的算法之美:从原子计数到栈的巧妙运用
linux·运维·服务器·算法·动态规划·代理模式·哈希算法
2501_941143733 小时前
缓存中间件Redis与Memcached在高并发互联网系统优化与实践经验分享
leetcode
ekprada3 小时前
DAY 18 推断聚类后簇的类型
算法·机器学习·支持向量机
生信大表哥3 小时前
Python单细胞分析-基于leiden算法的降维聚类
linux·python·算法·生信·数信院生信服务器·生信云服务器
玫瑰花店4 小时前
万字C++中锁机制和内存序详解
开发语言·c++·算法
靠沿4 小时前
Java数据结构初阶——LinkedList
java·开发语言·数据结构
Elias不吃糖5 小时前
LeetCode每日一练(209, 167)
数据结构·c++·算法·leetcode