请问大虾为什么构造树时要用“ *&“进行参数传递,为什么用”&" 就不行?多谢了!
如下是代码:
#include <iostream.h>
struct node
{
char data;
node * lchild,*rchild;
};
struct element
{
node *ptr;
int flag;
};
class tree
{
public :
tree (); //构造函数
~tree(); //析构函数
node *getroot () { return root;}
void creattree(node *&root); //构造树
void postorder(node *root); //后序遍历非递归算法
void release(node *r) ; //析造树
private:
node * root;
};
tree::tree() //构造
{
cout <<"请输入各结点的数据:"<<endl;
creattree(root);
}
tree ::~tree () //析构
{
release( root);
}
void tree::creattree (node *& cr) //构造树
{
char ch;
cin>>ch;
if (ch=='#')
cr=NULL;
else
{
cr=new node ;
cr->data =ch;
creattree(cr->lchild);
creattree(cr->rchild);
}
}
void tree::release (node *re) // 析造树
{
if (re!=NULL)
{
release(re->lchild);
release (re->rchild);
delete re;
}
}
void tree::postorder (node *root)//后序遍历树
{
int top =-1;
element s[100];
while (root!=NULL||top!=-1)
{
while (root!=NULL)
{
top++;
s[top].ptr=root;
s[top].flag=1;
root =root ->lchild ;
}
while ( top!=-1&&s[top].flag==2)
{
root=s[top--].ptr;
cout <<root->data;
}
if (top!=-1)
{
s[top].flag=2;
root=s[top].ptr->rchild;
}
else
return ;
}
}
void main ()
{
tree tr;
cout <<" 后序遍历为:"<<endl;
tr.postorder (tr.getroot ());
}