本题难度其实不算特别高,应该算是Hard里面比较容易的,但是确实没有想到。
    难点:

    • 要想明白Greedy在本题中是可行的:自下而上进行Greedy操作,如果不到万不得已,不新添加Camera.
      • Case 1: 左右子树都被监控,但是没有Camera,则本节点目前是未被监控状态,但是不需要Camera
      • Case 2: 左子树或者右子树未被监控,此时本节点必须有Camera
      • Case 3,其他,则本节点是被监控状态,但是不需要Camera
        • 左右都有Camera
        • 一边有Camera,另一边被监控,无Camera

    想明白Greedy为什么在Bottom-Up的思路下成立,本题的难度就是一道普通的Medium,代码如下:

    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode(int x) { val = x; }
    8. * }
    9. */
    10. class Solution {
    11. private static final int NOT_MONITOR = 0;
    12. private static final int MONITOR_NO_CAMERA = 1;
    13. private static final int MONITOR_CAMERA = 2;
    14. private int camera = 0;
    15. public int minCameraCover(TreeNode root) {
    16. int state = DFSHelper(root);
    17. return camera + (state == NOT_MONITOR ? 1 : 0);
    18. }
    19. private int DFSHelper(TreeNode node) {
    20. if (node == null) {
    21. return MONITOR_NO_CAMERA;
    22. }
    23. int l = DFSHelper(node.left);
    24. int r = DFSHelper(node.right);
    25. if (l == NOT_MONITOR || r == NOT_MONITOR) {
    26. ++camera;
    27. return MONITOR_CAMERA;
    28. }
    29. else if (l == MONITOR_NO_CAMERA && r == MONITOR_NO_CAMERA) {
    30. return NOT_MONITOR;
    31. }
    32. else {
    33. // (l == MONITOR_NO_CAMERA && r == MONITOR_CAMERA), (l == MONITOR_CAMERA && r == MONITOR_NO_CAMERA)
    34. return MONITOR_NO_CAMERA;
    35. }
    36. }
    37. }