题目

Given a binary tree, we install cameras on the nodes of the tree.

Each camera at a node can monitor its parent, itself, and its immediate children.

Calculate the minimum number of cameras needed to monitor all nodes of the tree.

Example 1:

image.png

  1. Input: [0,0,null,0,0]
  2. Output: 1
  3. Explanation: One camera is enough to monitor all nodes if placed as shown.

Example 2:

image.png

  1. Input: [0,0,null,0,null,0,null,null,0]
  2. Output: 2
  3. 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.

Note:

  1. The number of nodes in the given tree will be in the range [1, 1000].
  2. Every node has value 0.

题意

在二叉树中选取任意个结点放上一个照相机,每个照相机能覆盖当前结点、当前结点的父结点、当前结点的直接子结点。问最少需要放几个照相机能够覆盖所有结点。

思路

贪心。从最底下的结点开始往上,对于当前结点有三种情况需要放置照相机:(1) 当前结点的左子结点未被覆盖;(2) 当前结点的右子结点未被覆盖;(3) 当前结点未被覆盖,且无父结点。其他情况无需放置,最大化每个照相机的覆盖范围。


代码实现

Java

  1. class Solution {
  2. private int count;
  3. private Set<TreeNode> set;
  4. public int minCameraCover(TreeNode root) {
  5. count = 0;
  6. set = new HashSet<>();
  7. set.add(null);
  8. dfs(root, null);
  9. return count;
  10. }
  11. private void dfs(TreeNode root, TreeNode parent) {
  12. if (root == null) return;
  13. dfs(root.left, root);
  14. dfs(root.right, root);
  15. if (parent == null && !set.contains(root) || !set.contains(root.left) || !set.contains(root.right)) {
  16. set.add(root);
  17. set.add(root.left);
  18. set.add(root.right);
  19. set.add(parent);
  20. count++;
  21. }
  22. }
  23. }