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

[Swift]LeetCode1026.节点与其祖先之间的最大差值|MaximumDifferenceBetweenNodeandAn ...

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

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

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

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

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

Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B where V = |A.val - B.val| and A is an ancestor of B.

(A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.)

Example 1:

Input: [8,3,10,1,6,null,14,null,null,4,7,13]
Output: 7
Explanation: 
We have various ancestor-node differences, some of which are given below :
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.

Note:

  1. The number of nodes in the tree is between 2 and 5000.
  2. Each node will have value between 0 and 100000.

给定二叉树的根节点 root,找出存在于不同节点 A 和 B 之间的最大值 V,其中 V = |A.val - B.val|,且 A 是 B 的祖先。

(如果 A 的任何子节点之一为 B,或者 A 的任何子节点是 B 的祖先,那么我们认为 A 是 B 的祖先)

示例:

输入:[8,3,10,1,6,null,14,null,null,4,7,13]
输出:7
解释: 
我们有大量的节点与其祖先的差值,其中一些如下:
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
在所有可能的差值中,最大值 7 由 |8 - 1| = 7 得出。

提示:

  1. 树中的节点数在 2 到 5000 之间。
  2. 每个节点的值介于 0 到 100000 之间。

20ms
 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 maxAncestorDiff(_ root: TreeNode?) -> Int {
16         return traverse(root, Int.min, Int.max)
17     }
18     func traverse(_ node: TreeNode?, _ maxVal: Int, _ minVal: Int) -> Int {
19         guard let node = node else {
20             return abs(maxVal - minVal)
21         }
22         var maxVal = max(maxVal, node.val)
23         var minVal = min(minVal, node.val)
24         var maxDiff = maxVal - minVal
25         if let left = node.left {
26             maxDiff = max(maxDiff, traverse(left, maxVal, minVal))
27         }
28         if let right = node.right {
29             maxDiff = max(maxDiff, traverse(right, maxVal, minVal))
30         }
31         return maxDiff
32     }
33 }

24ms

  1 class Solution {
  2     // var ret = 0
  3     func maxAncestorDiff(_ root: TreeNode?) -> Int {
  4         if root == nil {
  5             return 0
  6         }
  7         
  8         var maxDiff = 0
  9         dfs(root!, root!.val, root!.val, &maxDiff)
 10         return maxDiff
 11     }
 12     
 13     func dfs(_ node: TreeNode, _ minVal: Int, _ maxVal: Int, _ maxDiff: inout Int) {        
 14 
 15         let a = abs(node.val - minVal)
 16         let b = abs(node.val - maxVal)
 17         maxDiff = getMax(a, b, maxDiff)
 18         
 19         if (node.left != nil && node.right == nil) {
 20             dfs(node.left!, min(minVal, node.left!.val), max(maxVal, node.left!.val), &maxDiff)
 21         } else if (node.left == nil && node.right != nil) {
 22             dfs(node.right!, min(minVal, node.right!.val), max(maxVal, node.right!.val), &maxDiff)
 23         } else if (node.left != nil && node.right != nil) {
 24             dfs(node.left!, min(minVal, node.left!.val), max(maxVal, node.left!.val), &maxDiff)
 25             dfs(node.right!, min(minVal, node.right!.val), max(maxVal, node.right!.val), &maxDiff)
 26         }
 27         return
 28     } 
 29     
 30     func getMax(_ a: Int, _ b: Int, _ c: Int) -> Int {
 31         return getMax(getMax(a,b), c)
 32     }
 33     
 34     func getMax(_ a: Int, _ b: Int) -> Int {
 35         if (a > b) {
 36             return a
 37         } else {
 38             return b
 39         }
 40     }
 41     
 42     func dfs(_ node: TreeNode) {        
 43         if (node.left == nil && node.right == nil) {
 44             // node is leaf
 45             node.leftMin = node.val
 46             node.leftMax = node.val
 47             node.rightMin = node.val
 48             node.rightMax = node.val
 49         }
 50         if (node.left != nil && node.right == nil) {
 51             // node has left child, has no right child
 52             node.rightMin = node.val
 53             node.rightMax = node.val
 54             dfs(node.left!)
 55             node.leftMin = min(node.left!.leftMin, node.left!.rightMin, node.val)
 56             // print("node", node.val, "has leftMin", node.leftMin)
 57             node.leftMax = max(node.left!.leftMax, node.left!.rightMax, node.val)
 58             // print("node", node.val, "has leftMax", node.leftMax)
 59         }
 60         else if (node.left == nil && node.right != nil) {
 61             // node has right child, has no left child
 62             node.leftMin = node.val
 63             node.leftMax = node.val
 64             dfs(node.right!)
 65             node.rightMin = min(node.right!.leftMin, node.right!.rightMin, node.val)
 66             // print("node", node.val, "has rightMin", node.rightMin)
 67             node.rightMax = max(node.right!.leftMax, node.right!.rightMax, node.val)
 68             // print("node", node.val, "has rightMax", node.rightMax)
 69         }
 70         else if (node.left != nil && node.right != nil) {
 71             dfs(node.left!)
 72             node.leftMin = min(node.left!.leftMin, node.left!.rightMin, node.val)
 73             node.leftMax = max(node.left!.leftMax, node.left!.rightMax, node.val)
 74             
 75             dfs(node.right!)
 76             node.rightMin = min(node.right!.leftMin, node.right!.rightMin, node.val)
 77             node.rightMax = max(node.right!.leftMax, node.right!.rightMax, node.val)
 78         }
 79         // print("node", node.val, ": lMin, lMax, rMin, rMax,", node.leftMin, node.leftMax, node.rightMin, node.rightMax)
 80 
 81         return
 82     }    
 83 }
 84 
 85 extension TreeNode {
 86     private struct Holder {
 87         static var leftMin = [String : Int]()
 88         static var leftMax = [String : Int]()
 89         static var rightMin = [String : Int]()
 90         static var rightMax = [String : Int]()
 91     }
 92     
 93     var leftMin: Int {
 94         get {
 95             let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
 96             return Holder.leftMin[tmpAddress] ?? 0
 97         }
 98         set(newValue) {
 99             let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
100             Holder.leftMin[tmpAddress] = newValue
101         }
102     }
103     
104     var rightMin: Int {
105             get {
106                 let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
107                 return Holder.rightMin[tmpAddress] ?? 0
108             }
109             set(newValue) {
110                 let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
111                 Holder.rightMin[tmpAddress] = newValue
112             }
113         }
114         
115     var leftMax: Int {
116         get {
117             let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
118             return Holder.leftMax[tmpAddress] ?? 0
119         }
120         set(newValue) {
121             let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
122             Holder.leftMax[tmpAddress] = newValue
123         }
124     }
125     
126     var rightMax: Int {
127         get {
128             let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
129             return Holder.rightMax[tmpAddress] ?? 0
130         }
131         set(newValue) {
132             let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
133             Holder.rightMax[tmpAddress] = newValue
134         }
135     }
136 }

32ms

 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 result = Int.min
16     func maxAncestorDiff(_ root: TreeNode?) -> Int {
17         guard let root = root else {
18             return 0
19         }
20         
21         dfsHelper(root)
22         
23         return result
24     }
25     
26     @discardableResult
27     fileprivate func dfsHelper(_ root: TreeNode?) -> (Int, Int) {
28         guard let root = root else {
29             return (Int.max, Int.min)
30         }
31         
32         if root.left == nil && root.right == nil {
33             return (root.val, root.val)
34         }
35         
36         let (leftTempMin, leftTempMax) = dfsHelper(root.left)
37         let (rightTempMin, rightTempMax) = dfsHelper(root.right)
38         
39         let currentMin = min(min(leftTempMin, rightTempMin), root.val)
40         let currentMax = max(max(root.val, rightTempMax), leftTempMax)
41         result = max(max(result, abs(root.val - currentMin)), abs(root.val - currentMax))
42         return (currentMin, currentMax)
43         
44     }
45 }

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 maxAncestorDiff(_ root: TreeNode?) -> Int {
16         return diffAndMin(root)?.diff ?? 0
17     }
18 
19     func diffAndMin(_ root: TreeNode?) -> (diff: Int, min: Int, max: Int)? {
20         guard let root = root else { return nil }
21 
22         var diffs = [Int](), mins = [root.val], maxs = [root.val]
23         if let (lDiff, lMin, lMax) = diffAndMin(root.left) {
24             diffs += [lDiff, abs(root.val - lMin), abs(root.val - lMax)]
25             mins.append(lMin)
26             maxs.append(lMax)
27         }
28         
29         if let (rDiff, rMin, rMax) = diffAndMin(root.right) {
30             diffs += [rDiff, abs(root.val - rMin), abs(root.val - rMax)]
31             mins.append(rMin)
32             maxs.append(rMax)
33         }
34         
35         return (diffs.max() ?? 0, mins.min()!, maxs.max()!)
36     }
37 }

Runtime: 416 ms

Memory Usage: 129.4 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     func maxAncestorDiff(_ root: TreeNode?) -> Int {
16         var list:[[Int]] = binaryTreePaths(root)
17         var res:Int = 0
18         for arr in list
19         {
20             res = max(res,getMaxDifference(arr))
21         }
22         return res
23     }
24     
25     func getMaxDifference(_ arr:[Int]) -> Int
26     {
27         var res:Int = 0
28         for i in 0..<arr.count
29         {
30             for j in (i + 1)..<arr.count
31             {
32                 res = max(res,abs(arr[i] - arr[j]))
33             }
34         }
35         return res
36     }
37     
38     //获取所有子树
39     func binaryTreePaths(_ root: TreeNode?) -> [[Int]] {
40         var list:[[Int]] = [[Int]]()
41         recuesive(root,&list,[Int]())
42         return list
43     }
44     
45     func recuesive(_ root:TreeNode?,_ list:inout [[Int]],_ arr:[Int])
46     {
47         if root == nil {return}
48         var arrNew:[Int] = arr
49         var arrRoot:[Int] = [root!.val]
50         if root?.left == nil && root?.right == nil
51         {
52             arrNew += arrRoot
53             list.append(arrNew)
54             return
55         }
56         arrRoot = arrNew + arrRoot
57         recuesive(root?.left,&list,arrRoot)
58         recuesive(root?.right,&list,arrRoot)
59     }
60 }

 


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Swift—继承发布时间:2022-07-13
下一篇:
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