-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0099.Recover Binary Search Tree.swift
61 lines (54 loc) · 1.57 KB
/
0099.Recover Binary Search Tree.swift
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
private var values = [Int]()
func recoverTree(_ root: TreeNode?) {
flatten(root)
let sortedValues = values.sorted()
var first = -1
var second = -1
for i in 0..<sortedValues.count {
if values[i] != sortedValues[i] {
if first == -1 {
first = values[i]
} else if second == -1 {
second = values[i]
}
}
}
update(root, first, second)
}
private func flatten(_ node: TreeNode?) {
guard let node = node else {
return
}
flatten(node.left)
values.append(node.val)
flatten(node.right)
}
private func update(_ node: TreeNode?, _ first: Int, _ second: Int) {
guard let node = node else {
return
}
update(node.left, first, second)
if node.val == first {
node.val = second
} else if node.val == second {
node.val = first
}
update(node.right, first, second)
}
}