#include<bits/stdc++.h>
using namespace std;
class node{
public:
int val;
node*left;
node*right;
node(int data){
val=data;
left=NULL;
right=NULL;
}
};
void insert(node*&root,int val){
queue<node*>q;
if(!root){
root=new node(val);
return ;
}
q.push(root);
while(!q.empty()){
node*temp=q.front();
q.pop();
if(temp->left)q.push(temp->left);
else{
temp->left=new node(val);
return;
}
if(temp->right) q.push(temp->right);
else{
temp->right=new node(val);
return;
}
}
}
void show(node*root){
queue<node*>q;
if(root) q.push(root);
else return;
while(!q.empty()){
node*temp=q.front();
q.pop();
cout<<temp->val<<" ";
if(temp->left) q.push(temp->left);
if(temp->right)q.push(temp->right);
}
cout<<endl;
}
node* search(node*root,int s){
if(root==NULL) return NULL;
if(root->val==s) return root;
node*left=search(root->left,s);
node*right=search(root->right,s);
if(left) return left;
else return right;
}
node*findparent(node*root,node*ele){
if(root==NULL) return root;
if(root->left==ele||root->right==ele) return root;
node*left=findparent(root->left,ele);
node*right=findparent(root->right,ele);
if(left) return left;
else return right;
}
int delete_node(node*root,int d){
node*loc=search(root,d);
if(!loc) return -1;
/*if(!loc)return -1;
if(loc->left){
loc->val=loc->left->val;
loc->left=NULL;
return 1;
}
if(loc->right){
loc->val=loc->right->val;
loc->right=NULL;
return 1 ;
}
node*parent=findparent(root,loc);
if(parent->left==loc) parent->left=NULL;
else parent->right=NULL;
return 1; */
queue<node*>q;
if(root) q.push(root);
else return -1;
node*temp=NULL;
while(!q.empty()){
temp=q.front();
q.pop();
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);
}
loc->val=temp->val;
node*parent=findparent(root,temp);
if(parent->left==temp) parent->left=NULL;
else parent->right=NULL;
return 1;
}
int main(){
node*root=NULL;
insert(root,10);
insert(root,20);
// show(root);
insert(root,30);
insert(root,40);
insert(root,50);
insert(root,60);
// show(root);
delete_node(root,20);
show(root);
}
No comments:
Post a Comment