?
2014-01-19 11:04:56 UTC
#include
#include
#include
typedef struct node{
int info;
struct node *right,*left;
}*nodeptr;
void display1(nodeptr Root);
void display2(nodeptr Root);
void display3(nodeptr Root);
void insert(nodeptr root,int x);
void del(nodeptr root,int x); */*for deletion*/*
nodeptr find(nodeptr root,int x);
int subdel(nodeptr root);
void display(nodeptr root);
void main(){
int c,x;
nodeptr root=NULL;
do{
printf("1.insert,2.delete,3.display,4.exit");
scanf("%d",&c);
switch(c){
case 1:
scanf("%d",&x);
if(root==NULL){
root=(nodeptr)malloc(sizeof(struct node));
root->info=x;
root->left=NULL;
root->left=NULL;}
else{
insert(root,x);} break;
case 2:
scanf("%d",&x);
if(root==NULL){printf("empty");}
else{
del(root,x);} break;
case 3:
if(root==NULL){printf("empty");}
else{
display(root);} break;
case 4:
exit(1); break;
default:
printf("wrong"); break;
}}while(c!=4);}
void del(nodeptr root,int x){
int k=0;
root= find(root,x);
if(root==NULL){ return;}
k=subdel(root);
if(k==0){
nodeptr temp=root;
temp=temp->right;
while(temp->left!=NULL){
temp=temp->left;}
root->info=temp->info;
subdel(temp);}}
nodeptr find(nodeptr root,int x){
if(root==NULL){printf("element not found"); return(NULL);}
if(root->info==x){
return(root);}
if(x
find(root->left,x);}
if(x>root->info){
find(root->right,x);}
}
int subdel(nodeptr root){ int k=0;
if((root->right==NULL)&&(root->left==NULL)){
free(root);
root=NULL; k=1; return(k);}
if((root->right==NULL)||(root->left==NULL)){
if(root->right==NULL){root->info=root->left->info;
free(root->left);
root->left==NULL;}
else{ root->info=root->right->info;
free(root->right);
root->right==NULL;} k=1; return(k);}
return(k);}
void display(nodeptr Root){
printf("preorder");
display1(Root);
printf("\n postorder");
display2(Root);
printf("\n inorder");
display3(Root);}
void display1(nodeptr Root){
nodeptr root=Root;
if(root!=NULL){
printf("%6d",root->info);
display1(root->left);
display1(root->right);
}}
void display2(nodeptr Root){
nodeptr root=Root;
if(root!=NULL){
display2(root->left);
display2(root->right);
printf("%6d",root->info);}}
void display3(nodeptr Root){
nodeptr root=Root;
if(root!=NULL){
display3(root->left);
printf("%6d",root->info);
display3(root->right);
printf("%6d",root->info); }
}
void insert(nodeptr root,int x){
nodeptr temp;
if(x
if(root->left==NULL){
temp=(nodeptr)malloc(sizeof(struct node));
temp->info=x; temp->left=NULL; temp->right=NULL; root->left=temp; return;}
else{ insert(root->left,x);} }
if(x>root->info){
if(root->right==NULL){
temp=(nodeptr)malloc(sizeof(struct node));
temp->info=x; temp->left=NULL; temp->right=NULL; root->right=temp; return;}
else{ insert(root->right,x);} }
}