Merge pull request #2435 from BanTanger/master

968. 监控二叉树 java 版本简化分支逻辑
This commit is contained in:
程序员Carl
2024-02-13 13:05:06 +08:00
committed by GitHub

View File

@ -369,8 +369,44 @@ class Solution {
}
```
简化分支版本:
```java
class Solution {
static int ans;
public int minCameraCover(TreeNode root) {
ans = 0; // 初始化
if(f(root) == 0) ans ++;
return ans;
}
// 定义 f 函数有三种返回值情况
// 0表示 x 节点没有被相机监控,只能依靠父节点放相机
// 1表示 x 节点被相机监控,但相机不是放在自身节点上
// 2表示 x 节点被相机监控,但相机放在自身节点上
public static int f(TreeNode x) {
if(x == null) return 1; // 空树认为被监控,但没有相机
// 左右递归到最深处
int l = f(x.left);
int r = f(x.right);
// 有任意一个子节点为空,就需要当前节点放相机,不然以后没机会
if(l == 0 || r == 0) {
ans ++; // 放相机
return 2;
}
// 贪心策略,左右子树都被监控,且没有监控到当前节点,
// 那么最有利的情况就是将相机放置在当前节点父节点上,
// 因为这样能多监控可能的子树节点和父父节点
if(l == 1 && r == 1) return 0;
// 剩下情况就是左右子树有可能为 2即当前节点被监控
return 1;
}
}
```
### Python
贪心(版本一)
```python
class Solution:
@ -757,4 +793,3 @@ public class Solution
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>