日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[Swift]LeetCode968.监控二叉树 | Binary Tree Cameras

發布時間:2023/12/2 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [Swift]LeetCode968.监控二叉树 | Binary Tree Cameras 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
?微信公眾號:山青詠芝(shanqingyongzhi)
?博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
?GitHub地址:https://github.com/strengthen/LeetCode
?原文地址:https://www.cnblogs.com/strengthen/p/10201562.html?
?如果鏈接不是山青詠芝的博客園地址,則可能是爬取作者的文章。
?原文已修改更新!強烈建議點擊原文地址閱讀!支持作者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

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:

    輸入:[0,0,null,0,0] 輸出:1 解釋:如圖所示,一臺攝像頭足以監控所有節點。

    示例 2:

    輸入:[0,0,null,0,null,0,null,null,0] 輸出:2 解釋:需要至少兩個攝像頭來監視樹的所有節點。 上圖顯示了攝像頭放置的有效位置之一。


    提示:

  • 給定樹的節點數的范圍是?[1, 1000]。
  • 每個節點的值都是 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 }

    ?

    轉載于:https://www.cnblogs.com/strengthen/p/10201562.html

    總結

    以上是生活随笔為你收集整理的[Swift]LeetCode968.监控二叉树 | Binary Tree Cameras的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。