# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minCameraCover(self, root: TreeNode) -> int:
'''
在安排选择摄像头的位置的时候,我们要从底向上进行推导,
因为尽量让叶子节点的父节点安装摄像头,这样摄像头的数量才是最少的,
这也是本道贪心的原理所在!
0:该节点无覆盖
1:本节点有摄像头
2:本节点有覆盖
'''
res = 0
def dfs(root):
nonlocal res
# 空节点,记为有覆盖
if not root: return 2
left = dfs(root.left)
right = dfs(root.right)
# 情况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 左节点覆盖,右节点无覆盖
if left == 0 or right == 0:
res += 1
return 1
# 情况3
# left == 1 && right == 2 左节点有摄像头,右节点有覆盖
# left == 2 && right == 1 左节点有覆盖,右节点有摄像头
# left == 1 && right == 1 左右节点都有摄像头
if left == 1 or right == 1: return 2
return -1 # 逻辑输出,实际上不会运行到这里
flag = dfs(root)
return res + 1 if flag == 0 else res # 情况4,root无覆盖