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+3)
- {
- x->right=insert_key(x->right,key);
- }
- else if(key<x->data-3)
- {
- x->left=insert_key(x->left,key);
- }
- else
- y=0;
- return x;
- }
- void printlevelorder(Node * x)
- {
- if(x==NULL)
- return;
- queue<Node*>q;
- q.push(x);
- while(q.empty()==false)
- {
- Node* y=q.front();
- cout<<y->data<<" ";
- q.pop();
- if (y->left != NULL)
- q.push(y->left);
- if (y->right != NULL)
- q.push(y->right);
- }
- }
- Node * findmin(Node* node)
- {
- Node* current = node;
- while (current && current->left != NULL)
- current = current->left;
- return current;
- }
- Node* deleteNode(Node* root, int key)
- {
- if (root == NULL)
- return root;
- if (key < root->data)
- root->left = deleteNode(root->left, key);
- else if (key > root->data)
- root->right = deleteNode(root->right, key);
- else
- {
- Node *temp ;
- if (root->left == NULL)
- {
- temp = root->right;
- free(root);
- return temp;
- }
- else if (root->right == NULL)
- {
- temp = root->left;
- free(root);
- return temp;
- }
- temp = findmin(root->right);
- root->data = temp->data;
- root->right = deleteNode(root->right,temp->data);
- }
- return root;
- }
- int main()
- {
- Node* root=NULL;
- y=1;
- while(1)
- {
- int n;
- cin>>n;
- if(n!=-1)
- {
- root=insert_key(root,n);
- }
- else
- break;
- }
- if(y==0)
- cout<<"All the inputs were not inserted."<<endl;
- int n;
- cin>>n;
- while(n--)
- {
- int key;
- cin>>key;
- deleteNode(root,key);
- printlevelorder(root);
- cout<<endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment