C++关于指针问题

来源:百度知道 编辑:UC知道 时间:2024/05/30 20:08:40
题目:在二叉树中删除以x为根的子树。

#include <iostream.h>

class Bitree{
public:
char data;
Bitree *Lchild,*Rchild;
Bitree()
{
int judge;
cout<<"输入数据"<<endl;
cin>>data;
cout<<"输入1建立左子树"<<endl;
cin>>judge;
if(judge==1)
Lchild=new Bitree;
else Lchild=NULL;
cout<<"输入1建立右子树"<<endl;
cin>>judge;
if(judge==1)
Rchild=new Bitree;
else Rchild=NULL;
return;
}
};

int Delete(Bitree *a,char b)
{
if(a->data==b)
return 1;
if(a->Lchild!=NULL)
{
if(Delete(a->Lchild,b))
a->Lchild=NULL;
}
if(a->Rchild!=NULL)
{
if(Delete(a->Rchild,b))
a->Rchild=NULL;
}
return 0;
}

void Display(Bitree *a)
{
cout<<a->data<<endl;
if(a->Lchild!=NULL)
{
cout<<"左子树

因为你使用指针,必须为指针开空间,而且在开空间时调用构造函数,才能进行初始话。
void main()
{
char k;
Bitree *root;
root = new Bitree; //加上这句话
cout<<"删除数据"<<endl;
cin>>k;
Delete(root,k);
Display(root);
cin.get();
}