968.监控二叉树
class Solution {
public:
int cnt = 0;
bool f(TreeNode*r) { // should not be null
// if(!r)return true;
if(!r->left&&!r->right)return false; // no monitor
bool lres = false;
if(r->left)res=f(r->left);
if(!res&&r->right)res=f(r->right);
if(res == true) return false;
else {
cnt ++ ;
return true;
}
}
int minCameraCover(TreeNode* r) {if(!r->left&&!r->right)return 1;
f(r);
return cnt;
}
};
想不明白:在二叉树中如何从低向上推导呢?
class Solution {
public:
int cnt = 0;
int f(TreeNode*p) {
// 0 -- 没有覆盖
// 1 -- 有覆盖了
// 2 -- 有摄像头
if(!p)return 1;
int l = f(p->left);
int r = f(p->right);
if (l==1 && r==1) return 0;//////
if (l==0 || r==0) {//////////////
cnt ++ ;
return 2;
}
return 1;
}
int minCameraCover(TreeNode* r) {if(!r->left&&!r->right)return 1;
if(f(r)==0)cnt++;///////
return cnt;
}
};
[0,0,null,null,0,0,null,null,0,0] 0 0 n n 0 0 n n 0 0