-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathRecover_Binary_Search_Tree.cc
89 lines (88 loc) · 2.57 KB
/
Recover_Binary_Search_Tree.cc
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(TreeNode * &pre, TreeNode *cnt, TreeNode * &p, TreeNode * &q) {
if (cnt == NULL) {
return;
}
dfs(pre, cnt->left, p, q);
if (pre != NULL && pre->val > cnt->val) {
if (p == NULL) {
p = pre;
}
q = cnt;
}
pre = cnt;
dfs(pre, cnt->right, p, q);
}
void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
TreeNode *pre = NULL, *p = NULL, *q = NULL;
dfs(pre, root, p, q);
if (p != NULL && q != NULL) {
int tmp = p->val;
p->val = q->val;
q->val = tmp;
}
}
};
//O(1) space solution
//Based on Morris Traversal algorithm (Construct Threads Binary Tree)
class Solution {
public:
void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!root) return;
TreeNode *pre = root;
TreeNode *cur = root;
TreeNode *tmp = NULL;
TreeNode *One = NULL;
TreeNode *Two = NULL;
bool found = false;
while (pre->left) pre = pre->left;
while (cur) {
if (!cur->left) {
if (cur->val < pre->val) {
if (!found) {
found = true;
One = pre;
}
Two = cur;
}
pre = cur;
cur = cur->right;
} else {
tmp = cur->left;
while (tmp->right && tmp->right != cur) {
tmp = tmp->right;
}
if (!tmp->right) {
tmp->right = cur;
cur = cur->left;
} else {
tmp->right = NULL;
if (cur->val < pre->val) {
if (!found) {
found = true;
One = pre;
}
Two = cur;
}
pre = cur;
cur = cur->right;
}
}
}
if (found) swap(One->val, Two->val);
}
};