Update 0968.监控二叉树.md

This commit is contained in:
jianghongcheng
2023-06-01 04:03:00 -05:00
committed by GitHub
parent 41dd31d826
commit ed4543b300

View File

@ -371,56 +371,104 @@ class Solution {
### Python
贪心(版本一)
```python
class Solution:
def minCameraCover(self, root: TreeNode) -> int:
# Greedy Algo:
# Greedy Algo:
# 从下往上安装摄像头跳过leaves这样安装数量最少局部最优 -> 全局最优
# 先给leaves的父节点安装然后每隔两层节点安装一个摄像头直到Head
# 0: 该节点未覆盖
# 1: 该节点有摄像头
# 2: 该节点有覆盖
def minCameraCover(self, root: TreeNode) -> int:
# 定义递归函数
result = [0] # 用于记录摄像头的安装数量
if self.traversal(root, result) == 0:
result[0] += 1
result = 0
# 从下往上遍历:后序(左右中)
def traversal(curr: TreeNode) -> int:
nonlocal result
return result[0]
if not curr: return 2
left = traversal(curr.left)
right = traversal(curr.right)
def traversal(self, cur: TreeNode, result: List[int]) -> int:
if not cur:
return 2
# Case 1:
# 左右节点都有覆盖
if left == 2 and right == 2:
return 0
left = self.traversal(cur.left, result)
right = self.traversal(cur.right, result)
# Case 2:
# left == 0 && right == 0 左右节点无覆盖
# left == 1 && right == 0 左节点有摄像头,右节点无覆盖
# left == 0 && right == 1 左节点有无覆盖,右节点摄像头
# left == 0 && right == 2 左节点无覆盖,右节点覆盖
# left == 2 && right == 0 左节点覆盖,右节点无覆盖
elif left == 0 or right == 0:
result += 1
return 1
# 情况1: 左右节点都有覆盖
if left == 2 and right == 2:
return 0
# Case 3:
# left == 1 && right == 2节点有摄像头,右节点覆盖
# left == 2 && right == 1 左节点有覆盖,右节点有摄像头
# left == 1 && right == 1 左右节点有摄像头
elif left == 1 or right == 1:
return 2
# 情况2:
# left == 0 && right == 0 左右节点覆盖
# left == 1 && right == 0 左节点有摄像头,右节点无覆盖
# left == 0 && right == 1 左节点无覆盖,右节点有摄像头
# left == 0 && right == 2 左节点无覆盖,右节点覆盖
# left == 2 && right == 0 左节点覆盖,右节点无覆盖
if left == 0 or right == 0:
result[0] += 1
return 1
# 其他情况前段代码均已覆盖
# 情况3:
# left == 1 && right == 2 左节点有摄像头,右节点有覆盖
# left == 2 && right == 1 左节点有覆盖,右节点有摄像头
# left == 1 && right == 1 左右节点都有摄像头
if left == 1 or right == 1:
return 2
if traversal(root) == 0:
result += 1
return result
```
贪心版本二利用elif精简代码
```python
class Solution:
# Greedy Algo:
# 从下往上安装摄像头跳过leaves这样安装数量最少局部最优 -> 全局最优
# 先给leaves的父节点安装然后每隔两层节点安装一个摄像头直到Head
# 0: 该节点未覆盖
# 1: 该节点有摄像头
# 2: 该节点有覆盖
def minCameraCover(self, root: TreeNode) -> int:
# 定义递归函数
result = [0] # 用于记录摄像头的安装数量
if self.traversal(root, result) == 0:
result[0] += 1
return result[0]
def traversal(self, cur: TreeNode, result: List[int]) -> int:
if not cur:
return 2
left = self.traversal(cur.left, result)
right = self.traversal(cur.right, result)
# 情况1: 左右节点都有覆盖
if left == 2 and right == 2:
return 0
# 情况2:
# left == 0 && right == 0 左右节点无覆盖
# left == 1 && right == 0 左节点有摄像头,右节点无覆盖
# left == 0 && right == 1 左节点无覆盖,右节点有摄像头
# left == 0 && right == 2 左节点无覆盖,右节点覆盖
# left == 2 && right == 0 左节点覆盖,右节点无覆盖
elif left == 0 or right == 0:
result[0] += 1
return 1
# 情况3:
# left == 1 && right == 2 左节点有摄像头,右节点有覆盖
# left == 2 && right == 1 左节点有覆盖,右节点有摄像头
# left == 1 && right == 1 左右节点都有摄像头
else:
return 2
```
### Go
```go