Leetcode之Binary Tree Cameras

題目:

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:

bst_cameras_01.pnguploading.4e448015.gif轉存失敗重新上傳取消

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

Example 2:

bst_cameras_02.pnguploading.4e448015.gif轉存失敗重新上傳取消

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.


Note:

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

代碼:

貪心法——

class Solution {
private:
    int ans = 0;

    int dfs(TreeNode* root) {
        if (root->left == NULL && root->right == NULL) return 0;
        int needCamera = 0;
        int covered = 0;
        if (root->left != NULL) {
            int state = dfs(root->left);
            if (state == 0) needCamera = 1;
            if (state == 1) covered = 1;
        }
        if (root->right != NULL) {
            int state = dfs(root->right);
            if (state == 0) needCamera = 1;
            if (state == 1) covered = 1;
        }
        if (needCamera) {
            ans++;
            return 1;
        }
        if (covered) return 2;
        return 0;
    }
    
public:
    int minCameraCover(TreeNode* root) {
        int state = dfs(root);
        if (state == 0) ans++;
        return ans;
    }
};

思路:令狀態0表示該結點還沒有被cover,1表示該結點上有一個照相機,2表示該結點上沒有照相機但是已經被cover了。(前提:這個結點對應的子樹除了它自己以外已經全都被cover了。

令葉結點的狀態爲0;對於一個結點,如果它的至少一個子結點狀態爲0,則它的狀態爲1;如果它的子結點狀態均不爲0,且至少一個子結點狀態爲1,則它的狀態爲2;否則它的狀態爲0。狀態爲1時照相機計數+1。

注意邊界條件(如果根節點的狀態爲0,則需要多加一個照相機)。[1]

我實在想不通怎麼證明這個解法的正確性(雖然我覺得它確實很有道理)。

DP法——

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章