算法--监控二叉树
Posted 前端学习记录簿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法--监控二叉树相关的知识,希望对你有一定的参考价值。
分析:对每个节点来说,为达到最小使用量,父节点可以监控所有的节点来,当子节点下没有更多的节点时,父节点安装监控即可,当子节点下有更多节点时,子节点安装即可。
思考如下:
function minCamera(tree){
let count = 0;
let arr = [tree];
while(arr.length){
let node = arr.pop();
let left = node.left,right=node.right;
// 可一个子节点下还有节点时,可不关注另外一个节点下是否还有节点
if(left&&(left.left||left.right)&&right&&(right.left||right.right)){
count+=2;
}else if((left&&(left.left||left.right)&&right)||(right&&(right.left||right.right)&&left)){
count+=2;
}else if(left||right){
count+=1;
}else if(count==0){
count+=1;
}
if(left&&left.left){
arr.push(left.left);
}
if(left&&left.right){
arr.push(left.right);
}
if(right&&right.left){
arr.push(right.left);
}
if(right&&right.right){
arr.push(right.right);
}
}
return count;
}
var ex1 = {
left: {
left: {},
right: {}
},
right: null
}
var ex2 = {
left: {
left: {
left: {
right:{}
}
}
}
}
var ex3={
left: {
left: {}
},
right: {
left: {},
right: {}
}
}
var ex4 = {
left: {
left: {}
},
right: {
left: {},
right: {
right: {}
}
}
}
var ex5 = {
}
var ex6 = {
left: {},
right: {}
}
var res1 = minCamera(ex1)
var res2 = minCamera(ex2)
var res3 = minCamera(ex3)
var res4 = minCamera(ex4)
var res5 = minCamera(ex5)
var res6 = minCamera(ex6)
console.log(res1,res2,res3,res4,res5,res6);
2 2 3 1 1
其他参考解法:1、参考链接:leetcode 每日一题 968 监控二叉树_Mosiclone的博客-CSDN博客
class getCamera{
// 递归遍历整个树
// status有三个状态:0不能被监测到,1自身装了摄像头,2没装摄像头可以被监视
count = 0;
dfs(node){
if(!node) return 2; //null节点返回2,这样叶子节点的值j就是0
const left = this.dfs(node.left);
const right = this.dfs(node.right);
if(left ==0 ||right ==0){
this.count++;
return 1;
}
if(left ==1 || right==1) return 2;
return 0;
}
minCameraCover(root){
if(!root) return 0;
if(!root.right&&!root.left) return 1;
if(this.dfs(root)==0) this.count++;
return this.count;
}
}
以上是关于算法--监控二叉树的主要内容,如果未能解决你的问题,请参考以下文章