@@ -316,28 +316,44 @@ public:
316
316
### Java
317
317
``` java
318
318
class Solution {
319
- private int count = 0 ;
319
+ int res = 0 ;
320
320
public int minCameraCover (TreeNode root ) {
321
- if (trval(root) == 0 ) count++ ;
322
- return count;
321
+ // 对根节点的状态做检验,防止根节点是无覆盖状态 .
322
+ if (minCame(root)== 0 ){
323
+ res++ ;
324
+ }
325
+ return res;
323
326
}
324
-
325
- private int trval (TreeNode root ) {
326
- if (root == null ) return - 1 ;
327
-
328
- int left = trval(root. left);
329
- int right = trval(root. right);
330
-
331
- if (left == 0 || right == 0 ) {
332
- count++ ;
327
+ /**
328
+ 节点的状态值:
329
+ 0 表示无覆盖
330
+ 1 表示 有摄像头
331
+ 2 表示有覆盖
332
+ 后序遍历,根据左右节点的情况,来判读 自己的状态
333
+ */
334
+ public int minCame (TreeNode root ){
335
+ if (root== null ){
336
+ // 空节点默认为 有覆盖状态,避免在叶子节点上放摄像头
333
337
return 2 ;
334
338
}
335
-
336
- if (left == 2 || right == 2 ) {
339
+ int left= minCame(root. left);
340
+ int right= minCame(root. right);
341
+
342
+ // 如果左右节点都覆盖了的话, 那么本节点的状态就应该是无覆盖,没有摄像头
343
+ if (left== 2 && right== 2 ){
344
+ // (2,2)
345
+ return 0 ;
346
+ }else if (left== 0 || right== 0 ){
347
+ // 左右节点都是无覆盖状态,那 根节点此时应该放一个摄像头
348
+ // (0,0) (0,1) (0,2) (1,0) (2,0)
349
+ // 状态值为 1 摄像头数 ++;
350
+ res++ ;
337
351
return 1 ;
352
+ }else {
353
+ // 左右节点的 状态为 (1,1) (1,2) (2,1) 也就是左右节点至少存在 1个摄像头,
354
+ // 那么本节点就是处于被覆盖状态
355
+ return 2 ;
338
356
}
339
-
340
- return 0 ;
341
357
}
342
358
}
343
359
```
@@ -391,7 +407,7 @@ class Solution:
391
407
result += 1
392
408
393
409
return result
394
- ```
410
+ ```
395
411
396
412
### Go
397
413
``` go
0 commit comments