-
Notifications
You must be signed in to change notification settings - Fork 0
/
recover_bst.cpp
45 lines (36 loc) · 850 Bytes
/
recover_bst.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
// Problem Link : https://leetcode.com/problems/recover-binary-search-tree/description/
class Solution {
private :
TreeNode* first ;
TreeNode* last ;
TreeNode* middle ;
TreeNode* prev ;
private :
void inorder(TreeNode *root){
if(root==NULL){
return ;
}
inorder(root->left) ;
if(prev!=NULL && prev->val>root->val){
if(first==NULL){
first = prev ;
middle = root ;
}
last = root ;
}
prev = root ;
inorder(root->right) ;
}
public:
void recoverTree(TreeNode* root) {
first=middle=last=NULL ;
prev = new TreeNode(INT_MIN) ;
inorder(root) ;
if(first && last){
swap(first->val , last->val) ;
}
else if(first && middle){
swap(first->val , middle->val) ;
}
}
};