Skip to content

Commit 32c54b4

Browse files
committed
修改 968 监控二叉树 Java 代码,增加注释
1 parent 6226b26 commit 32c54b4

File tree

1 file changed

+33
-17
lines changed

1 file changed

+33
-17
lines changed

problems/0968.监控二叉树.md

Lines changed: 33 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -316,28 +316,44 @@ public:
316316
### Java
317317
```java
318318
class Solution {
319-
private int count = 0;
319+
int res=0;
320320
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;
323326
}
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+
// 空节点默认为 有覆盖状态,避免在叶子节点上放摄像头
333337
return 2;
334338
}
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++;
337351
return 1;
352+
}else{
353+
// 左右节点的 状态为 (1,1) (1,2) (2,1) 也就是左右节点至少存在 1个摄像头,
354+
// 那么本节点就是处于被覆盖状态
355+
return 2;
338356
}
339-
340-
return 0;
341357
}
342358
}
343359
```
@@ -391,7 +407,7 @@ class Solution:
391407
result += 1
392408

393409
return result
394-
```
410+
```
395411

396412
### Go
397413
```go

0 commit comments

Comments
 (0)