968. Binary Tree Cameras

📋 Đề Bài

You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.

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

 

Example 1:

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

Example 2:

Input: root = [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.

 

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • Node.val == 0

🧠 Thuật Toán & Kỹ Thuật

DFS (Tìm kiếm theo chiều sâu)Tree Traversal (Duyệt cây)
⏱️ Thời gian O(V+E)
💾 Không gian O(V)

💻 Lời Giải

C++ 0968-binary-tree-cameras.cpp
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

class Solution {
private:
    int res = 0;
    
public:
    int dfs(TreeNode* root) {
        if (!root) {
            return 1;
        }
        int node_left = dfs(root->left);
        int node_right = dfs(root->right);
        if (node_left == 0 or node_right == 0) {
            res++;
            return 2;
        }
        if (node_left == 2 or node_right == 2) {
            return 1;
        }
        return 0;
    }
    
    int minCameraCover(TreeNode* root) {
        if (dfs(root) == 0) {
            res++;
        }
        return res;
    }
};