-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecover-binary-search-tree.cpp
43 lines (41 loc) · 1.12 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) {}
* };
*/
class Solution {
public:
TreeNode *fwd = nullptr, *fwd_cur = new TreeNode(numeric_limits<int>::min());
TreeNode *bwd = nullptr, *bwd_cur = new TreeNode(numeric_limits<int>::max());
void recoverTree(TreeNode *root) {
inWalkFwd(root);
inWalkBwd(root);
swap(fwd->val, bwd->val);
}
void inWalkFwd(TreeNode *root){
if (root == nullptr || fwd != nullptr)
return;
inWalkFwd(root->left);
if (root->val < fwd_cur->val){
fwd = fwd_cur;
return;
}
fwd_cur = root;
inWalkFwd(root->right);
}
void inWalkBwd(TreeNode *root){
if (root == nullptr || bwd != nullptr)
return;
inWalkBwd(root->right);
if (root->val > bwd_cur->val){
bwd = bwd_cur;
return;
}
bwd_cur = root;
inWalkBwd(root->left);
}
};