File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments