力扣-贪心-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;
    }   
};
相关推荐
CoderYanger17 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz17 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab
夏鹏今天学习了吗17 小时前
【LeetCode热题100(72/100)】前 K 个高频元素
leetcode
稚辉君.MCA_P8_Java17 小时前
DeepSeek 插入排序
linux·后端·算法·架构·排序算法
多多*17 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven
.YM.Z19 小时前
【数据结构】:排序(一)
数据结构·算法·排序算法
Chat_zhanggong34519 小时前
K4A8G165WC-BITD产品推荐
人工智能·嵌入式硬件·算法
百***480719 小时前
【Golang】slice切片
开发语言·算法·golang
墨染点香19 小时前
LeetCode 刷题【172. 阶乘后的零】
算法·leetcode·职场和发展
做怪小疯子19 小时前
LeetCode 热题 100——链表——反转链表
算法·leetcode·链表