力扣-贪心-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;
    }   
};
相关推荐
橙几6 分钟前
击败了90%的解法?Two Sum 从 O(n²) 到 O(n) 的优化之路
算法
叶子爱分享20 分钟前
经典排序算法之归并排序(Merge Sort)
算法·排序算法
珹洺26 分钟前
C++算法竞赛篇:DevC++ 如何进行debug调试
java·c++·算法
Norvyn_736 分钟前
LeetCode|Day18|20. 有效的括号|Python刷题笔记
笔记·python·leetcode
呆呆的小鳄鱼1 小时前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香1 小时前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely1 小时前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_07121 小时前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_1 小时前
cf1925B&C
数据结构·算法
YuTaoShao2 小时前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先