-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecoverBinarySearchTree.cpp
More file actions
65 lines (57 loc) · 1.47 KB
/
RecoverBinarySearchTree.cpp
File metadata and controls
65 lines (57 loc) · 1.47 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
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
void recoverTree(TreeNode *root) {
TreeNode *p = NULL;
TreeNode *c = NULL;
TreeNode *lep = NULL;
TreeNode *lec = NULL;
TreeNode *rep = NULL;
TreeNode *rec = NULL;
while (root) {
if (root->left == NULL) {
p = c;
c = root;
root = root->right;
}
else {
TreeNode* t = root->left;
while (t->right && t->right != root)
t = t->right;
if (t->right == NULL) {
t->right = root;
root = root->left;
continue;
}
else {
t->right = NULL;
p = c;
c = root;
root = root->right;
}
}
if (p && c && p->val > c->val) {
if (!lep && !lec) {
lep = p;
lec = c;
}
else {
rep = p;
rec = c;
}
}
}
if (lep && rep) {
std::swap(lep->val, rec->val);
}
else if (lep && !rep) {
std::swap(lep->val, lec->val);
}
return;
}
};