Binary Tree Cameras

Problem Id: 968 Difficulty: Hard Tag: Dynamic Programming Tag: Tree Tag: Depth-first Search


Intuition

This is a DP problem based on tree as data structure.

We use 'C' to mark cameras, '-' to mark empty node, 'N' to mark node which is not visited yet. For a tree with below structure, there are several situations.

  0
 / \
1   2

We could do a post-order DFS to solve this problem. When we are visiting node 0, there could be 3 state for node 1. First is that there are camera in node 1. Second is node 1 is monitored by one of its child. And the third in that node 1 is not under monitoring.

We could get the minimum of cameras for each state in node 0 easily from the 3 states of its 2 children. So we could use it to solve this problem recursivly.

Solution


# 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:
        return min(self._helper(root)[0:2])

    def _helper(self, node):
        if node is None:
            return 1, 0, 0
        l, r = self._helper(node.left), self._helper(node.right)
        camera = min(l) + min(r) + 1
        monitored = min(l[0] + r[0], l[0] + r[1], l[1] + r[0])
        not_monitored = l[1] + r[1]
        return camera, monitored, not_monitored