Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- int y;
- struct node
- {
- int data;
- struct node* left;
- struct node* right;
- };
- typedef struct node Node;
- Node* create_node(int item)
- {
- Node* new_node=new Node();
- if(new_node==NULL)
- cout<<"Error"<<endl;
- else
- {
- new_node->data=item;
- new_node->left=new_node->right=NULL;
- }
- return new_node;
- }
- Node* insert_key(Node* x,int key)
- {
- Node* new_node=create_node(key);
- if(x==NULL)
- return new_node;
- if(key>x->data)
- {
- x->right=insert_key(x->right,key);
- }
- else if(key<x->data)
- {
- x->left=insert_key(x->left,key);
- }
- return x;
- }
- Node * findmin(Node* node)
- {
- struct node* current = node;
- while (current && current->left != NULL)
- current = current->left;
- return current;
- }
- Node * findmax(Node* node)
- {
- Node* current = node;
- while (current && current->right != NULL)
- current = current->right;
- return current;
- }
- void find_pre_suc(Node* root, Node*& pre, Node*& suc, int val)
- {
- if (root == NULL)
- return ;
- if (root->data == val)
- {
- Node* temp;
- if (root->left != NULL)
- {
- temp = root->left;
- pre = findmax(temp) ;
- }
- if (root->right != NULL)
- {
- temp = root->right ;
- suc = findmin(temp) ;
- }
- return ;
- }
- if (root->data>val)
- {
- suc = root ;
- find_pre_suc(root->left, pre, suc, val) ;
- }
- else
- {
- pre = root ;
- find_pre_suc(root->right, pre, suc, val) ;
- }
- }
- bool find_node(Node* node, int val)
- {
- if (node == NULL)
- return false;
- if (node->data == val)
- return true;
- if(find_node(node->left,val))
- return true;
- else
- return find_node(node->right,val);
- }
- int main()
- {
- Node* root=NULL;
- while(1)
- {
- int n;
- cin>>n;
- y=1;
- if(n!=-1)
- root=insert_key(root,n);
- else
- break;
- }
- int k;
- cout<<"Number of test-cases"<<endl;
- cin>>k;
- for(int j=0; j<k; j++)
- {
- int p;
- cin>>p;
- if(find_node(root,p)==false)
- cout<<"Reservation not found!"<<endl;
- else
- {
- Node* pre = NULL, *suc = NULL;
- find_pre_suc(root,pre,suc,p);
- if (pre != NULL)
- cout << pre->data <<" ";
- else
- cout << "NULL" <<" ";
- if (suc != NULL)
- cout << suc->data <<" ";
- else
- cout << "NULL" <<" ";
- cout<<endl;
- }
- }
- }
Add Comment
Please, Sign In to add comment