📅  最后修改于: 2023-12-03 15:11:21.922000             🧑  作者: Mango
在监控二叉树(每个节点有左右子节点或者为叶子节点)的所有节点的情况下,需要安装一定数量的摄像头,设计一个算法,使得摄像头数量最少。
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.count = 0
def minCameraCover(self, root: TreeNode) -> int:
# 对根节点进行监控
if not root:
return 0
if not root.left and not root.right:
return 1
self.count = 0
if not root.left:
# 左子树为空,必须在根节点放置摄像头
self.count += 1
self.helper(root.right)
elif not root.right:
# 右子树为空,必须在根节点放置摄像头
self.count += 1
self.helper(root.left)
else:
# 左右子树都不为空
self.helper(root)
return self.count
def helper(self, root: TreeNode):
if not root:
return
if not root.left and not root.right:
return
if not root.left:
# 左子树为空,必须在右孩子节点放置摄像头
self.count += 1
self.helper(root.right.left)
self.helper(root.right.right)
elif not root.right:
# 右子树为空,必须在左孩子节点放置摄像头
self.count += 1
self.helper(root.left.left)
self.helper(root.left.right)
else:
# 左右子树都不为空
self.helper(root.left.left)
self.helper(root.left.right)
self.helper(root.right.left)
self.helper(root.right.right)