-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaxDiffBetweenNodeAndAncestor.swift
More file actions
72 lines (50 loc) · 1.89 KB
/
Copy pathMaxDiffBetweenNodeAndAncestor.swift
File metadata and controls
72 lines (50 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Leetcode- 1026
/*
Given the root of a binary tree, find the maximum value v for which there exist 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.
*/
// Brute force approach
class Solution {
var absHighestValue = Int.min
func maxAncestorDiff(_ root: TreeNode?) -> Int {
var stack = [TreeNode]()
guard let rootNode = root else {
return 0
}
stack.append(rootNode)
while !stack.isEmpty {
let lastNode = stack.removeLast()
absHighestValue = max(findAbsValueForANode(root: lastNode), absHighestValue)
if let leftNode = lastNode.left {
stack.append(leftNode)
}
if let rightNode = lastNode.right {
stack.append(rightNode)
}
}
return absHighestValue
}
func findAbsValueForANode(root: TreeNode?) -> Int {
var stack = [TreeNode]()
var lowestValue = Int.max
var highestValue = Int.min
guard let rootNode = root else {
return 0
}
stack.append(rootNode)
while !stack.isEmpty {
let lastNode = stack.removeLast()
lowestValue = min(lastNode.val, lowestValue)
highestValue = max(lastNode.val, highestValue)
if let leftNode = lastNode.left {
stack.append(leftNode)
}
if let rightNode = lastNode.right {
stack.append(rightNode)
}
}
let rootValue = rootNode.val
let maxVal = max(abs(rootValue - highestValue), abs(rootValue - lowestValue))
return maxVal
}
}