Binary Tree Cameras


Last updated


Last updated
Input:
[0,0,null,0,0]
Output:
1
Explanation:
One camera is enough to monitor all nodes if placed as shown.Input:
[0,0,null,0,null,0,null,null,0]
Output:
2
Explanation:
At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.The number of nodes in the given tree will be in the range [1, 1000].
Every node has value 0. MONITORED\_NOCAM = 1
MONITORED\_WITHCAM = 2# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minCameraCover(self, root: TreeNode) -> int:
NOT_MONITORED = 0
MONITORED_NOCAM = 1
MONITORED_WITHCAM = 2
cameras = 0
if not root:
return 0
def dfs(root: TreeNode) -> int:
nonlocal cameras
if not root:
return MONITORED_NOCAM
left = dfs(root.left)
right = dfs(root.right)
if left == MONITORED_NOCAM and right ==MONITORED_NOCAM:
return NOT_MONITORED
elif left == NOT_MONITORED or right == NOT_MONITORED:
cameras += 1
return MONITORED_WITHCAM
else:
return MONITORED_NOCAM
top = dfs(root)
return cameras+1 if top== NOT_MONITORED else cameras