-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrecover-binary-search-tree.cc
49 lines (48 loc) · 1.51 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
/**
* 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 recoverTree(TreeNode *root) {
//using morris inorder traversal
TreeNode *pre(nullptr);
pair<TreeNode*, TreeNode*> nodes{nullptr, nullptr};
while(root) {
if(root->left == nullptr) {
//visit root
if(pre && pre->val >= root->val) {
if(nodes.first == nullptr) nodes.first = pre;
nodes.second = root;
}
pre = root;
root = root->right;
continue;
}
//find the lastest node in left sub-tree
TreeNode *largest(root->left);
for(; largest->right && largest->right != root; largest = largest->right);
if(largest->right == nullptr) {
largest->right = root;
root = root->left;
}
else {
largest->right = nullptr;
//visit root
if(pre && pre->val >= root->val) {
if(nodes.first == nullptr) nodes.first = pre;
nodes.second = root;
}
pre = root;
root = root->right;
}
}
if(nodes.first && nodes.second)
swap(nodes.first->val, nodes.second->val);
}
};