diff --git a/problems/0968.监控二叉树.md b/problems/0968.监控二叉树.md index 305f3ae5..9743ca2b 100644 --- a/problems/0968.监控二叉树.md +++ b/problems/0968.监控二叉树.md @@ -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 -