修改 968 监控二叉树 Java 代码,增加注释

This commit is contained in:
Wayne
2022-03-02 16:03:14 +08:00
parent 6226b26a1d
commit 32c54b4a56

View File

@ -316,28 +316,44 @@ public:
### Java ### Java
```java ```java
class Solution { class Solution {
private int count = 0; int res=0;
public int minCameraCover(TreeNode root) { public int minCameraCover(TreeNode root) {
if (trval(root) == 0) count++; // 对根节点的状态做检验,防止根节点是无覆盖状态 .
return count; if(minCame(root)==0){
res++;
}
return res;
} }
/**
private int trval(TreeNode root) { 节点的状态值:
if (root == null) return -1; 0 表示无覆盖
1 表示 有摄像头
int left = trval(root.left); 2 表示有覆盖
int right = trval(root.right); 后序遍历,根据左右节点的情况,来判读 自己的状态
*/
if (left == 0 || right == 0) { public int minCame(TreeNode root){
count++; if(root==null){
// 空节点默认为 有覆盖状态,避免在叶子节点上放摄像头
return 2; return 2;
} }
int left=minCame(root.left);
if (left == 2 || right == 2) { int right=minCame(root.right);
// 如果左右节点都覆盖了的话, 那么本节点的状态就应该是无覆盖,没有摄像头
if(left==2&&right==2){
//(2,2)
return 0;
}else if(left==0||right==0){
// 左右节点都是无覆盖状态,那 根节点此时应该放一个摄像头
// (0,0) (0,1) (0,2) (1,0) (2,0)
// 状态值为 1 摄像头数 ++;
res++;
return 1; return 1;
}else{
// 左右节点的 状态为 (1,1) (1,2) (2,1) 也就是左右节点至少存在 1个摄像头
// 那么本节点就是处于被覆盖状态
return 2;
} }
return 0;
} }
} }
``` ```
@ -391,7 +407,7 @@ class Solution:
result += 1 result += 1
return result return result
``` ```
### Go ### Go
```go ```go