You are given the root
of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return the minimum number of cameras needed to monitor all nodes of the tree.
Example 1:
Consider the following binary tree:
0
/ \
0 null
/ \
0 0
If we place a camera at the root node, we can monitor the entire tree. Therefore, the minimum number of cameras needed is 1.
Example 2:
Consider the following binary tree:
0
/ \
0 null
/ \
0 null
/ \
0 null
/ \
null 0
In this case, we need at least two cameras. One possible configuration is to place cameras at the nodes with values of 0 that are children of the root's left child, and at the child node with value 0, in the lowest level. Hence, the output should be 2.
Constraints:
[1, 1000]
.Node.val == 0
Can you provide an algorithm to solve this problem efficiently?
You are given the root of a binary tree. You need to place cameras on some nodes such that all nodes are monitored. Each camera at a node can monitor its parent, itself, and its immediate children. The goal is to return the minimum number of cameras needed to monitor all nodes of the tree.
A brute-force approach would involve trying all possible combinations of camera placements and then selecting the configuration with the fewest cameras that covers all nodes. This approach is highly inefficient.
A more efficient approach can be achieved using a bottom-up recursion (or post-order traversal) combined with a greedy strategy. For each node, we can define three states:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def minCameraCover(root: TreeNode) -> int:
camera_count = 0
def dfs(node: TreeNode) -> int:
nonlocal camera_count
if not node:
return 0 # Covered
left = dfs(node.left)
right = dfs(node.right)
if left == 2 or right == 2:
camera_count += 1
return 1 # Has camera
if left == 1 or right == 1:
return 0 # Covered
return 2 # Not covered
if dfs(root) == 2:
camera_count += 1
return camera_count