968. 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:
在这里插入图片描述
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.

方法1: greedy + dynamic programming

discussion: https://leetcode.com/problems/binary-tree-cameras/discuss/211246/C%2B%2B-Greedy%2BDFS-O(n)-Time-4ms-with-Explanation

思路:

用greedy的做法,能把责任往上推就往上推,因为parent可以照顾到更多的节点。We put camera at as higher level (closer to root) as possible. We use post-order DFS here. The return value of DFS() has following meanings. 0: there is no camera at this node, and it’s not monitored by camera at either of its children, which means neither of child nodes has camera. 1: there is no camera at this node; however, this node is monitored by at least 1 of its children, which means at least 1 of its children has camera. 2: there is a camera at this node.

Complexity

Time complexity: O(n)
Space complexity: O(h)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minCameraCover(TreeNode* root) {
        int sum = 0;
        if (camHelper(root, sum) == 0) sum++; // if root is not monitored, we place an additional camera here
        return sum;
    }
    
    int camHelper(TreeNode* root, int & sum) {
        if (!root) return 1;
        int left = camHelper(root -> left, sum);
        int right = camHelper(root -> right, sum);
        if (left == 0 || right == 0) { // if at least 1 child is not monitored, we need to place a camera at current node 
            sum++;
            return 2;
        }
        else if (left == 1 && right == 1) { // if both children are monitored but have no camera, we don't need to place a camera here. We place the camera at its parent node at the higher level. 
            return 0;
        }
        return 1; // if at least 1 child has camera, the current node is monitored. Thus, we don't need to place a camera here 
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值