File tree 1 file changed +88
-0
lines changed
1 file changed +88
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* Hacker Blocks */
2
+ /* Title - Recover BST */
3
+ /* Created By - Akash Modak */
4
+ /* Date - 26/10/2020 */
5
+
6
+
7
+ // Two elements of a binary search tree (BST) are swapped by mistake. Tell us the 2 values swapping which the tree will be restored.
8
+
9
+ // Input Format
10
+ // First line contains n denoting the input size.
11
+ // Next line contains n space separated integers denoting the preorder input of the tree.
12
+
13
+ // NOTE : -1 indicates that the node does not exist.
14
+
15
+ // Constraints
16
+ // 1 <= n <= 10^5
17
+ // Your recovery algorithm should work in O(n) time.
18
+
19
+ // Output Format
20
+ // Print the two integers in space separated manner. The output should be sorted.
21
+
22
+ // Sample Input
23
+ // 3 2 1 -1 -1 -1 5 6 4 -1 -1 -1 -1
24
+ // Sample Output
25
+ // 5 6
26
+ // Explanation
27
+ // The tree looks like
28
+
29
+ // 3
30
+ // / \
31
+ // 2 5
32
+ // / /
33
+ // 1 6
34
+ // /
35
+ // 4
36
+ // Swapping 5 and 6 makes the tree a BST.
37
+
38
+ #include < bits/stdc++.h>
39
+ using namespace std ;
40
+ vector<int > v;
41
+ class node {
42
+ public:
43
+ int data;
44
+ node* left,*right;
45
+ node (int d){
46
+ data = d;
47
+ left=right=NULL ;
48
+ }
49
+ };
50
+ node* build (){
51
+ int d;
52
+ cin>>d;
53
+
54
+ if (d==-1 ){
55
+ return NULL ;
56
+ }
57
+ node* root = new node (d);
58
+ root->left = build ();
59
+ root->right = build ();
60
+ return root;
61
+ }
62
+ void inorder (node* root){
63
+ if (root==NULL )
64
+ return ;
65
+
66
+ inorder (root->left );
67
+ v.push_back (root->data );
68
+ inorder (root->right );
69
+ }
70
+ pair<int ,int > checkSwap (){
71
+ int x=-1 ,y=-1 ,i;
72
+ for (i=0 ;i<v.size ()-1 ;i++){
73
+ if (v[i+1 ]<v[i]){
74
+ y=v[i+1 ];
75
+ if (x==-1 )
76
+ x=v[i];
77
+ }
78
+ }
79
+ return {x,y};
80
+ }
81
+ int main () {
82
+ /* code here */
83
+ node* root = build ();
84
+ inorder (root);
85
+ pair<int ,int > p = checkSwap ();
86
+ cout<<min (p.first ,p.second )<<" " <<max (p.first ,p.second )<<endl;
87
+ return 0 ;
88
+ }
You can’t perform that action at this time.
0 commit comments