[Swift Weekly Contest 117]LeetCode968.二叉树摄像机 | 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:

 

输入:[0,0,null,0,0]

输出:1

说明:如果按图中所示放置,一个摄像头足以监视所有节点。

例2:

 

输入:[0,0,null,0,null,0,null,null,0]

输出:2

说明:至少需要两个摄像头来监控树的所有节点。上图显示了相机放置的有效配置之一。

注:

  1. 给定树中的节点数将在范围[1000]内。
  2. 每个节点都有值0。

52ms

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public var val: Int
 5  *     public var left: TreeNode?
 6  *     public var right: TreeNode?
 7  *     public init(_ val: Int) {
 8  *         self.val = val
 9  *         self.left = nil
10  *         self.right = nil
11  *     }
12  * }
13  */
14 class Solution {
15     func minCameraCover(_ root: TreeNode?) -> Int {
16         var ans:[Int] = mh(root)
17         return min(ans[1], ans[2])
18     }
19     
20     func mh(_ ro:TreeNode?)-> [Int]
21     {
22         if ro == nil
23         {
24             var ans:[Int] = [Int](repeating:0,count:3)
25             ans[1] = 1000000
26             return ans
27         }
28         var l:[Int] = mh(ro!.left)
29         var r:[Int] = mh(ro!.right)
30         var ans:[Int] = [Int](repeating:0,count:3)
31         ans[0] = l[2] + r[2];
32         ans[1] = 1000000;
33         ans[2] = 1000000;
34         for i in 0..<3
35         {
36             for j in 0..<3
37             {
38                 ans[1] = min(ans[1], l[i]+r[j]+1)
39             }
40             if i==0 {continue}
41             ans[2] = min(ans[2], l[1]+r[i])
42             ans[2] = min(ans[2], l[i]+r[1])
43         }
44         return ans
45     }
46 }
 

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10201562.html