-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path99. Recover Binary Search Tree.cpp
65 lines (63 loc) · 2.06 KB
/
99. Recover Binary Search Tree.cpp
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
/*
near 1 hours to understand the morris algo
write code 40min.
// no idea about O(1) space. Searched and fount Morris.
// for this problem, inorder visit could make the tree to sorted array, then:
// 1 3 2 4 -> one drop 3->2, find swap i,i+1->(2,3)
// 1 5 3 4 2 6 -> two drop 5->3 and 4->2, find swap i,j->(5,2)
// 2 1 4 3 6 5 ->three or more dorp, no ans.
// find all slot of inorder preNode->val > cur->val
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode* root) {
TreeNode* cur=root;
vector<TreeNode*> drops;
TreeNode* lastPtr = nullptr;
while(cur) {
TreeNode* prv=cur->left;
if(!prv) {
// visit cur now.
if (lastPtr&&lastPtr->val > cur->val) {
drops.push_back(lastPtr);
drops.push_back(cur);
}
lastPtr = cur;
cur = cur->right;
continue;
}
while(prv->right&&prv->right!=cur) {
prv = prv->right;
}
if(prv->right==cur) {
prv->right = nullptr;
// visit cur now.
if (lastPtr&&lastPtr->val > cur->val) {
drops.push_back(lastPtr);
drops.push_back(cur);
}
lastPtr = cur;
cur = cur->right;
} else {
prv->right = cur;
cur = cur->left;
}
}
if (drops.size()==2)
swap(drops[0]->val, drops[1]->val);
else if (drops.size()==4)
swap(drops[0]->val, drops[3]->val);
else cout<<"gg"<<endl;
}
};