forked from fanfank/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recover-binary-search-tree.cpp
43 lines (43 loc) · 1.03 KB
/
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
/*
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//O(1) space
class Solution {
public:
vector<TreeNode*> v; //push at most 2 elements
TreeNode *last;
void traverse(TreeNode *root) {
if(root == NULL)
return;
traverse(root->left);
if(last == NULL) {
//just do nothing
}
else if(v.size() == 0) {
if(root->val < last->val) {
v.push_back(last);
v.push_back(root);
}
}
else {
if(root->val < last->val) {
v[1] = root;
}
}
last = root;
traverse(root->right);
}
void recoverTree(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
v.clear();
last = NULL;
traverse(root);
swap(v[0]->val, v[1]->val);
}
};