标签:Binary 结点 set null Tree add nodes 0968 root
Binary Tree Cameras (H)
题目
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.
题意
在二叉树中选取任意个结点放上一个照相机,每个照相机能覆盖当前结点、当前结点的父结点、当前结点的直接子结点。问最少需要放几个照相机能够覆盖所有结点。
思路
贪心。从最底下的结点开始往上,对于当前结点有三种情况需要放置照相机:(1) 当前结点的左子结点未被覆盖;(2) 当前结点的右子结点未被覆盖;(3) 当前结点未被覆盖,且无父结点。其他情况无需放置,最大化每个照相机的覆盖范围。
代码实现
Java
class Solution {
private int count;
private Set<TreeNode> set;
public int minCameraCover(TreeNode root) {
count = 0;
set = new HashSet<>();
set.add(null);
dfs(root, null);
return count;
}
private void dfs(TreeNode root, TreeNode parent) {
if (root == null) return;
dfs(root.left, root);
dfs(root.right, root);
if (parent == null && !set.contains(root) || !set.contains(root.left) || !set.contains(root.right)) {
set.add(root);
set.add(root.left);
set.add(root.right);
set.add(parent);
count++;
}
}
}
标签:Binary,结点,set,null,Tree,add,nodes,0968,root 来源: https://www.cnblogs.com/mapoos/p/14774489.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。