Recover Binary Search Tree

#include <bits/stdc++.h>
using namespace std;

class node

{

public:
int data;
node*left;
node*right;
node(int d)
{
    data=d;
    left=NULL;
    right=NULL;
}

};

int i;

node* builttree()

{

int d;
cin>>d;
if(d==-1)
{
    return NULL;
}
node*root=new node(d);
root->left=builttree();
root->right=builttree();
if(root->left!=NULL && i==0)
    {
    if(root->data < root->left->data)
    {
        cout<<root->data<<" "<<root->left->data<<" ";
        i++;
    }
    }
    if(root->right!=NULL && i==0)
    {
      if(root->data > root->right->data)
    {
        cout<<root->data<<" "<<root->left->data<<" ";
        i++;
    }  
    }
return root;

}
// void recoverTree(node* root) {
// if(root==NULL)
// {
// return;
// }

// recoverTree(root->left);
// recoverTree(root->right);
// return;
// }
int main() {
/* code here /
i=0;
node
root=builttree();
// recoverTree(root);
return 0;
}
it only pass one test case can you plzz tell me what the mistake in this code

Hey @Pranav7g
Please share your code in Coding blocks IDE

Hey @Pranav7g
Here is a testcase for which your code will not even run : 4 10 -1 -1 6 -1 2 -1 -1

Here is the algorithm:

  1. Construct inorder traversal of the tree. It should be an almost sorted list where only two elements are swapped.
  2. Identify two swapped elements x and y in an almost sorted array in linear time.

why my code is wrong

Make tree for the above example and you will understand.
Any 2 nodes can be swapped

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.