このプログラムは、バイナリツリーノードの挿入、削除を行う必要があります。 問題は、削除後にツリー要素を表示すると、プログラムにエラーが表示されることです。私のプログラムで何が間違っているのを助けてください。誰でもこのプログラムの何が間違っているか知っていますか?
#include <iostream.h>
#include <stdlib.h>
#include <string>
class Tnode
{
public:
class Tnode *left;
class Tnode *right;
int info;
};
class tree: public Tnode
{
public:
int top;
Tnode *root;
tree()
{
root=NULL;
top=0;
}
void insert(int ch)
{
Tnode *temp,*temp1;
if(root== NULL)
{
root=new Tnode;
root->info=ch;
root->left=NULL;
root->right=NULL;
return;
}
temp1=new Tnode;
temp1->info=ch;
temp1->right=temp1->left=NULL;
temp=search(root,ch);
if(temp->info>ch)
temp->left=temp1;
else
temp->right=temp1;
}
Tnode *search(Tnode *temp,int ch)
{
if(root== NULL)
{
cout <<"no node present";
return NULL;
}
if(temp->left==NULL && temp->right== NULL)
return temp;
if(temp->info>ch)
{
if(temp->left==NULL) return temp;
search(temp->left,ch);
}
else
{
if(temp->right==NULL) return temp;
search(temp->right,ch);
}
}
void display(Tnode *temp)
{
if(temp==NULL)
return;
display(temp->left);
cout<<temp->info;
display(temp->right);
}
Tnode *getposition(Tnode *root, int x)
{
Tnode *temp;
temp=root;
while(temp&&temp->info != x)
((temp->info>x)?(temp=temp->left):(temp=temp->right));
return(temp);
}
Tnode *getleft_right_most(Tnode *temp)
{
Tnode *m=temp->left;
while(temp->right)
temp=temp->right;
return temp;
}
Tnode *getfather(Tnode *root, Tnode *temp)
{
Tnode *h=root;
while(h->left!=temp&&h->right!=temp)
((h->info>temp->info)?h=h->left : h=h->right);
return h;
}
Tnode *del(Tnode *temp, Tnode *f)
{
if(temp->left&&temp->right)
if(temp->right)
{
(f->left==temp)?f->left=temp->right : f->left=temp->right;
temp->right=0;
}
if(temp->left)
{
(f->right==temp)?f->right=temp->left : f->right=temp->right;
temp->left=0;
}
free(temp);
}
Tnode *delroot(Tnode *root)
{
Tnode *d=root;
if((d->right)&&!(d->left))
{
root=d->right;
d->right=0;
}
else if((d->left)&&!(d->right))
{
root=d->left;
d->left=0;
}
else
root=0;
return d;
}
Tnode *delprocess(Tnode *root, int key)
{
Tnode *d=root;
Tnode *temp,*f,*t,*Re;
if(root->info==key)
{
Re=delroot(d);
return(Re);
}
else
{
temp=getposition(d,key);
if(temp->left!=0&&temp->right!=0)
{
t=getleft_right_most(temp);
temp->info=t->info;
temp=t;
}
f=getfather(d,temp);
Re=del(temp,f);
return(Re);
}
}
};
main()
{
tree t1;
int ch,n,i;
while(1)
{
cout <<"\n1.INSERT\n2.DELETE NUMBER\n3.DISPLAY\n4.EXIT\nEnter your choice:";
cin >> ch;
switch(ch)
{
case 1: do{
cout <<"\nenter the elements you want to insert:";
cin >> ch;
cout<<"\nto exit insert the number -1.";
if(ch!=-1)
t1.insert(ch);
}while(ch!=-1);
break;
case 2: t1.display(t1.root);break;
case 3: cout<<"\nto delete a number of your insertion enter it : ";
cin>>n;
t1.root=t1.delprocess(t1.root,n);
cout<<"\nthe tree after deletion is : ";
t1.display(t1.root); break;
case 4: exit(1);
}
}
}
...おそらくもっとありますが、エラーを示して?それはすべてあなたが言うことができるのですか?私は同様の方法で答えることができます:あなたのプログラムに何が問題なのですか?よく、それはバグがあります... –