Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c86a4ba

Browse files
committed
20190514
1 parent 3865230 commit c86a4ba

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎code/lc968.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package code;
2+
/*
3+
* 968. Binary Tree Cameras
4+
* 题意:在树上放置camera, 覆盖整棵树,一个camera可以监视自身,父节点和孩子节点,问最少camera数量
5+
* 难度:Hard
6+
* 分类:Dynamic Programming, Tree, Depth-first Search
7+
* 思路:贪心算法,尽量让父节点放置
8+
* Tips:
9+
*/
10+
public class lc968 {
11+
public class TreeNode {
12+
int val;
13+
TreeNode left;
14+
TreeNode right;
15+
TreeNode(int x) { val = x; }
16+
}
17+
int res;
18+
public int minCameraCover(TreeNode root) {
19+
if(root==null) return 0;
20+
int flag = dfs(root);
21+
if(flag==3) return res+1; //如果是3,代表root没被覆盖
22+
return res;
23+
}
24+
25+
public int dfs(TreeNode tn){
26+
// 1代表被覆盖了,但该点没有camera。left,right都不为3的话,贪心算法,父节点不需要放置
27+
// 2代表被覆盖了,该点有camera,父节点不需要放置
28+
// 3代表没有被覆盖,所以父节点要放置
29+
if(tn==null) return 1;
30+
int left = dfs(tn.left);
31+
int right = dfs(tn.right);
32+
if( left==3 || right==3){
33+
res+=1; //在该节点放置
34+
return 2;
35+
}
36+
if( left==2 || right==2 ) return 1;
37+
return 3;
38+
}
39+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /