力扣-贪心-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;
    }   
};
相关推荐
凌冰_9 小时前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
Pniubi10 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展
戴·菲瑜10 小时前
为什么PPO难以做出顶级棋类引擎
算法·博弈论·rl·ppo
在所不辞兄12 小时前
为什么数字孪生驱动的产线标定需要在线更新机制,而不能一次标定后长期沿用?
人工智能·神经网络·其他·算法·机器学习
郝学胜-神的一滴16 小时前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
文丑颜不良啊16 小时前
LeetCode3401~3420题目解析
java·leetcode
AvocadoZeroOneOI17 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
文丑颜不良啊17 小时前
LeetCode3421~3440题目解析
java·leetcode
cjz389919 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
console.log('npc')21 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习