力扣-贪心-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;
    }   
};
相关推荐
信奥卷王1 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵1 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
徐小黑ACG3 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
码完就睡3 小时前
数据结构——红黑树
数据结构
码爸3 小时前
数据结构详细介绍
数据结构
Navigator_Z3 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
北极有牛4 小时前
cpp学习笔记--常量指针
java·开发语言·算法
GPU实战笔记4 小时前
云端 GPU 训练的账户余额提醒:它能说明什么,不能说明什么?
深度学习·算法·成本管理·gpu云计算·云端训练
浮链序4 小时前
怎么证明"你这个模型是偷我的"——把蒸馏变成取证工具
算法·安全·llm