5.编写一个将二叉树的所有叶子结点从左向右链接成单链表的算法。
#include
struct node
{
int data;
node * lchild,*rchild,*link;
};
node *create(void) //建立二叉树链表
{
node *p;
int ch;
cin>>ch;
if(ch==0)
return NULL;
else
{
p=new node;
p->data=ch;
p->lchild=create();
p->rchild=create();
return p;
}
}
node *q,*tail,*head=0;
node *c(node *p)
{
if(p!=NULL)
{
if(p->lchild==NULL&&p->rchild==NULL)
{
q=new node;
q->data=p->data;
q->link=0;
if(head==0)
{
head=q;
tail=0;
}
else
tail->link=q;
tail=q;
}
c(p->lchild);
c(p->rchild);
}
return head;
}
void print(node *p)
{
while(p!=NULL)
{
cout<
p=p->link;
}
}
void main() //主函数
{
node *s,*h;
s=create();
h=c(s);
print(h);
}