-
Notifications
You must be signed in to change notification settings - Fork 8
/
recover-binary-search-tree.js
104 lines (96 loc) · 1.69 KB
/
recover-binary-search-tree.js
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// Two elements of a binary search tree (BST) are swapped by mistake.
//
// Recover the tree without changing its structure.
//
// Example 1:
//
//
// Input: [1,3,null,null,2]
//
// 1
// /
// 3
// \
// 2
//
// Output: [3,1,null,null,2]
//
// 3
// /
// 1
// \
// 2
//
//
// Example 2:
//
//
// Input: [3,1,4,null,null,2]
//
// 3
// / \
// 1 4
// /
// 2
//
// Output: [2,1,4,null,null,3]
//
// 2
// / \
// 1 4
// /
// 3
//
//
// Follow up:
//
//
// A solution using O(n) space is pretty straight forward.
// Could you devise a constant space solution?
//
//
//https://discuss.leetcode.com/topic/29161/share-my-solutions-and-detailed-explanation-with-recursive-iterative-in-order-traversal-and-morris-traversal/2
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {void} Do not return anything, modify root in-place instead.
*/
var recoverTree = function(root) {
var first = null
var second = null
var pred = null
var prev = null
var curr = root
while (curr) {
if (prev && curr.val <= prev.val) {
first = first || prev
second = curr
}
if (curr.left) {
pred = curr.left
while (pred.right && pred.right !== curr) {
pred = pred.right
}
if (pred.right === curr) {
pred.right = null
prev = curr
curr = curr.right
} else {
pred.right = curr
curr = curr.left
}
} else {
prev = curr
curr = curr.right
}
}
var temp = first.val
first.val = second.val
second.val = temp
};