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:
- The number of nodes in the tree is between
2
and5000
. - Each node will have value between
0
and100000
.
给定二叉树的根节点
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 得出。
提示:
- 树中的节点数在
2
到5000
之间。 - 每个节点的值介于
0
到100000
之间。
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 = 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 }
原文地址:https://www.cnblogs.com/strengthen/p/10704595.html
时间: 2024-11-13 09:06:12