• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

[Swift]LeetCode1123.最深叶节点的最近公共祖先|LowestCommonAncestorofDeepestLeaves ...

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

Given a rooted binary tree, find the lowest common ancestor of its deepest leaves.

Recall that:

  • The node of a binary tree is a leaf if and only if it has no children
  • The depth of the root of the tree is 0, and if the depth of a node is d, the depth of each of its children is d+1.
  • The lowest common ancestor of a set S of nodes is the node A with the largest depth such that every node in S is in the subtree with root A

Example 1:

Input: root = [1,2,3]
Output: [1,2,3]

Example 2:

Input: root = [1,2,3,4]
Output: [4]

Example 3:

Input: root = [1,2,3,4,5]
Output: [2,4,5] 

Constraints:

  • The given tree will have between 1 and 1000 nodes.
  • Each node of the tree will have a distinct value between 1 and 1000.

给你一个有根节点的二叉树,找到它最深的叶节点的最近公共祖先。

回想一下:

  • 叶节点 是二叉树中没有子节点的节点
  • 树的根节点的 深度 为 0,如果某一节点的深度为 d,那它的子节点的深度就是 d+1
  • 如果我们假定 A 是一组节点 S 的 最近公共祖先,<font color="#c7254e" face="Menlo, Monaco, Consolas, Courier New, monospace">S</font> 中的每个节点都在以 A 为根节点的子树中,且 A 的深度达到此条件下可能的最大值。 

示例 1:

输入:root = [1,2,3]
输出:[1,2,3]

示例 2:

输入:root = [1,2,3,4]
输出:[4]

示例 3:

输入:root = [1,2,3,4,5]
输出:[2,4,5] 

提示:

  • 给你的树中将有 1 到 1000 个节点。
  • 树中每个节点的值都在 1 到 1000 之间。

40ms
 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 lcaDeepestLeaves(_ root: TreeNode?) -> TreeNode? {
16         return _lcaDeepestLeaves(root).0
17     }
18     
19     func _lcaDeepestLeaves(_ root: TreeNode?) -> (TreeNode?, Int) {
20         guard let root = root else { return (nil, 0) }
21         
22         if root.left == nil && root.right == nil {
23             return (root, 1)
24         } else if root.left == nil {
25             let right = _lcaDeepestLeaves(root.right)
26             return (right.0, right.1 + 1)
27         } else if root.right == nil {
28             let left = _lcaDeepestLeaves(root.left)
29             return (left.0, left.1 + 1)
30         } else {
31             let left = _lcaDeepestLeaves(root.left)
32             let right = _lcaDeepestLeaves(root.right)
33 
34             if left.1 > right.1 {
35                 return (left.0, left.1 + 1)
36             } else if right.1 > left.1 {
37                 return (right.0, right.1 + 1)
38             } else {
39                 return (root, left.1 + 1)
40             }
41         }
42     }
43 }

44ms

 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 lcaDeepestLeaves(_ root: TreeNode?) -> TreeNode? {
16         return helper(root).1
17     }
18 
19     func helper(_ root: TreeNode?) -> (Int, TreeNode?) {
20         if root == nil {
21             return (0, root)
22         }
23 
24         let left = helper(root!.left)
25         let right = helper(root!.right)
26         if left.0 > right.0 {
27             return (left.0+1, left.1)
28         } else if left.0 < right.0  {
29             return (right.0+1, right.1)
30         } else {
31             return (left.0+1, root)
32         }
33     }
34 }

Runtime: 48 ms

Memory Usage: 21.1 MB
 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     var DP:Int = 0
16     func lcaDeepestLeaves(_ root: TreeNode?) -> TreeNode? {
17         DP = dfs(root);
18         return dfs2(root, 0).0
19     }
20     
21     func dfs(_ root: TreeNode?) -> Int
22     {
23         var ans:Int = 0
24         if root?.left != nil
25         {
26             ans = max(ans, 1 + dfs(root?.left))
27         }
28         if root?.right != nil
29         {
30             ans = max(ans, 1 + dfs(root?.right))
31         }
32         return ans
33     }
34     
35     func dfs2(_ root: TreeNode?,_ dp:Int) -> (TreeNode?,Bool)
36     {
37         var p1:(TreeNode?,Bool) = (root,false)
38         var p2:(TreeNode?,Bool) = (root,false)
39         if root?.left != nil
40         {
41             p1 = dfs2(root!.left, dp + 1)
42         }
43         if root?.right != nil
44         {
45             p2 = dfs2(root!.right, dp + 1)
46         }
47         if p1.1
48         {
49             if p2.1
50             {
51                 return (root,true)
52             }
53             else 
54             {
55                 return p1
56             }
57         }
58         else
59         {
60             if p2.1 {return p2}
61             else
62             {
63                 if dp == DP
64                 {
65                     return (root, true)
66                 }
67                 else
68                 {
69                     return (root, false)
70                 }
71             }
72         }
73     }
74 }

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     var res: TreeNode?
16     var sz = [Int](repeating: 0, count: 1020)
17     var dep = [Int](repeating: 0, count: 1020)
18     var mxd = 0
19     func dfs(_ x: TreeNode, _ d: Int) {
20         sz[x.val] = 1
21         dep[x.val] = d
22         mxd = max(mxd, d)
23         if x.left != nil {
24             dfs(x.left!, d+1)
25             sz[x.val] += sz[x.left!.val]
26         }
27 
28         if x.right != nil {
29             dfs(x.right!, d+1)
30             sz[x.val] += sz[x.right!.val]
31         }
32     }
33 
34     func dfs2(_ x: TreeNode) -> Int{
35 
36         if dep[x.val] == mxd {
37             res = x
38             return x.val
39         }
40         var le = -1
41         var ri = -1;
42         if x.left != nil {
43             le = dfs2(x.left!)
44         }
45         if x.right != nil {
46             ri = dfs2(x.right!)
47         }
48         if le != -1 && ri != -1 {
49             res = x
50         }
51         return max(le,  ri)
52     }
53     
54     func lcaDeepestLeaves(_ root: TreeNode?) -> TreeNode? {
55         dfs(root!, 0)
56         dfs2(root!)
57         return res
58     }
59 }

64ms

 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 extension TreeNode: Hashable {
15     public static func == (lhs: TreeNode, rhs: TreeNode) -> Bool {
16         return lhs === rhs
17     }
18     public func hash(into hasher: inout Hasher) {
19         hasher.combine(self.val)
20     }
21 }
22 
23 class Solution {
24     typealias TreeNodeInfo = (parent: TreeNode?, level: Int)
25     var info = Dictionary<TreeNode?,TreeNodeInfo>()
26     var maxLevel = 0
27     func traverse(root: TreeNode?, level: Int)  {
28         if root == nil {
29             return
30         }
31         let tempLexel =  level + 1
32         if nil != root?.left {
33             if tempLexel > maxLevel {
34                 maxLevel =  tempLexel
35             }
36             info[root?.left] = (root, tempLexel)
37             traverse(root: root?.left, level: tempLexel)
38         }
39         if nil != root?.right {
40             if tempLexel > maxLevel {
41                 maxLevel =  tempLexel
42             }
43             info[root?.right] = (root, tempLexel)
44             traverse(root: root?.right, level: tempLexel)
45         }
46     }
47     func lcaDeepestLeaves(_ root: TreeNode?) -> TreeNode? {
48         if root == nil {
49             return nil
50         }
51         traverse(root: root, level: 0)
52         info[root] = (nil,0)
53         let depestLeaves = info.filter { (arg0) -> Bool in
54             let (_, value) = arg0
55             return value.level == maxLevel
56         }
57         if depestLeaves.count == 1{
58             return depestLeaves.first!.key
59         }
60         var currentSet = Set<TreeNode?>(depestLeaves.keys)
61         while currentSet.count > 1 {
62 
63             var parents = Set<TreeNode?>()
64             for node in currentSet {
65                 parents.insert(info[node]?.parent)
66             }
67             currentSet = parents
68         }
69         return currentSet.first!
70     }
71 }

76ms

 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 lcaDeepestLeaves(_ root: TreeNode?) -> TreeNode? {
16 
17     guard let rootNode = root, rootNode.left != nil || rootNode.right != nil else { return root }
18 
19     var stack = [[TreeNode]]()
20     var currentRow = [TreeNode]()
21     var nextRow =  [rootNode]
22 
23     var parents = [Int: TreeNode]()
24 
25     repeat {
26       currentRow = nextRow
27       nextRow = []
28       stack.append(currentRow)
29 
30       for node in currentRow {
31         let children = [node.left, node.right].compactMap { $0 }
32         if let left = node.left {
33           parents[left.val] = node
34         }
35         if let right = node.right {
36           parents[right.val] = node
37         }
38         nextRow.append(contentsOf: children)
39       }
40 
41     } while nextRow.count > 0
42 
43     var deepestLeaves = stack.popLast()!
44     var deepestLeavesSet = Set<Int>(deepestLeaves.compactMap { $0.val })
45 
46     while deepestLeavesSet.count > 1 {
47       deepestLeaves = deepestLeaves.compactMap { parents[$0.val] }
48       deepestLeavesSet = Set<Int>(deepestLeaves.map { $0.val })
49     }
50 
51     return deepestLeaves.first!
52   }
53 }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
IOS开发入门之一从零开始学习Swift发布时间:2022-07-13
下一篇:
OpenStack对象存储——Swift发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap