968. Binary Tree Cameras

本文介绍了一种使用深度优先搜索算法来确定在二叉树中安装最少数量摄像头的方法,以确保所有节点都被监控到。通过递归地评估每个节点的状态,可以有效计算所需的最小摄像头数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

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

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/*使用深度优先搜索,从叶节点开始遍历。深度优先搜索函数参数为根节点,返回值一个枚举类,分别是camera(该节点有相机),covered(该节点没有相机但被覆盖),None(该节点没有相机也没有被覆盖)。先判断该节点的两个子节点是否有None状态,如果有,则该节点为camera,相机数+1;再判断该节点的子节点是否有camera状态,如果有,则该节点状态为covered,否则该节点为None状态。对于空节点,返回covered状态。如果根节点返回None状态,则相机数需+1;

*/
 

class Solution {
public:
    int minCameraCover(TreeNode* root) {
        State r_state = dfs(root);
        if(r_state == None)
        {
            ans++;
        }
        return ans;
    }
private:
    enum State{ None,Covered,Camera};
    int ans = 0;
    State dfs(TreeNode* root)
    {
        if(!root) return Covered;
        State lc = dfs(root->left);
        State rc = dfs(root->right);
        if(lc == None || rc == None)
        {
            ans++;
            return Camera;
        }
        if(lc == Camera || rc == Camera)
        {
            return Covered;
        }
        return None;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值