思路
用true和false作为放置了摄像头,会有局限,就是没法判断以下情况
所以要用数字代表三种状态
- 2:有覆盖
- 1:有摄像头
- 0:无覆盖
两个节点都被覆盖时,要返回0
两个节点有一个无覆盖就要返回1
两个节点有一个有摄像头,返回覆盖即可
代码
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;
}
};