LeetCode C++ 968. Binary Tree Cameras【Tree/DFS】困難

myRealization發表於2020-09-27

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:
在這裡插入圖片描述

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

Example 2:
在這裡插入圖片描述

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:

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

題意:給定一個二叉樹,我們在樹的節點上安裝攝像頭。節點上的每個攝影頭都可以監視其父物件、自身及其直接子物件。計算監控二叉樹的所有節點所需的最小攝像頭數量


思路 分析結點狀態

後序遍歷,詳細分析見程式碼:

class Solution {
public:
    int total = 0;
    //0:節點沒有安裝監視器,且監視得到,當前節點不需要安裝監視器,暗示上層節點不需要裝監視器 
    //1:節點沒有安裝監視器,且監視不到,暗示上層節點需要裝監視器
    //2:節點安裝了監視器,暗示上層節點不需要裝監視器 
    int dfs(TreeNode *root) {
        if (root == nullptr) return 0; //如果為空,視作可以監視,但是上層不用安裝監視器
        int left = dfs(root->left), right = dfs(root->right); //後序遍歷左右子樹,探查其節點狀態
        //1 0, 0 1, 1 2, 2 1, 1 1
        if (left == 1 || right == 1) { //如果左右子樹有一個沒有安裝監視器,且監視不到
            ++total;                   //當前節點需要按照監視器
            return 2;                  //節點安裝了監視器,返回2,上層節點不用安裝監視器
        } //0 2, 2 0, 2 2
        if (left == 2 || right == 2)  //如果左右子樹有一個安裝監視器而另一個監視得到或都裝了,當前節點就不用安裝監視器
            return 0;                 //當前節點可以被監視,上層節點不需要安裝監視器,返回0
        return 1;                     //探查的左右節點狀態都為0,於是返回1,暗示上層節點需要安裝監視器
    }
    int minCameraCover(TreeNode* root) {
        if (root == nullptr) return total; //空樹則不用監視器
        if (dfs(root) == 1) ++total; //如果根節點看不到,加一監視器
        return total;
    }
};

相關文章