-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecover Binary Search Tree.cpp
More file actions
37 lines (36 loc) · 965 Bytes
/
Recover Binary Search Tree.cpp
File metadata and controls
37 lines (36 loc) · 965 Bytes
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
/**
* 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) {
if (!root) return;
vector<TreeNode *> mistake;
stack<TreeNode *> stk;
TreeNode *cur = root;
TreeNode *last = NULL;
while (!stk.empty() || cur) {
if (cur) {
stk.push(cur);
cur = cur->left;
} else {
cur = stk.top();
stk.pop();
if (last && last->val > cur->val) {
mistake.push_back(last);
mistake.push_back(cur);
}
last = cur;
cur = cur->right;
}
}
if (mistake.size() > 0)
swap(mistake.front()->val, mistake.back()->val);
}
};