数据结构:二叉树的叶子结点连成单链表
添加时间: 2007-4-9 1:16:18 作者: 程序员认证参考 阅读次数:51 来源: http://www.d9soft.com
【题目】请设计一个算法,把二叉树的叶子结点按从左到右的顺序连成一个单链表。二叉树按lchild - rchild 的方式存储,链接时用叶子结点的rchild 域存放指针。
【来源】长沙铁道学院99年第四(3)题(8’)
【解答】
#include
#include
#include
#include
typedef struct node{
char c;
int count;
struct node *left,*right;
}bnode;
bnode *k,*m; // 分别记录叶子链表的第一及当前结点的前驱
bnode *creatree(bnode *ptr,char ch) // 建二叉树
{ int result;bnode *p,*r; // p 指向当前结点的最近的父结点
p=NULL;r=ptr;
while(r){ // 检查 是否存在相同结点
result=(int)(r->c)-(int)(ch);
if(!result){r->count+=1;return r;}
else
{p=r;
r=result<0?r->right:r->left;
}
}
r=(struct node *)malloc(sizeof(bnode));// 建新结点
r->left=r->right=NULL;
r->c=(char)malloc(sizeof(char));
r->c=ch;r->count=1;
if(!ptr)return r;
else if(result>0) p->left=r;
else p->right=r;
return r;
}
leaflink(bnode *root)
{
if(!root)return;
if(root->left==NULL&&root->right==NULL){
if(k==NULL)k=m=root; // 保存找到的第一个叶子结点(k指针)
else {m->right=root;m=m->right;}}
if(root->left)leaflink(root->left);
if(root->right)leaflink(root->right);
return;
}
main()
{
char *s;
bnode *root=NULL;
printf("Input a string:");
scanf("%s",s);
do{
if(!root)root=creatree(root,*s);
else creatree(root,*s);
s+=1;
}while(*s);
leaflink(root); // 将叶结点链成链表
while(k){printf("%c",k->c);k=k->right;} // 输出该链表
}
【分析】建一个一般的二叉树如果采用递归的话,将对调用该二叉树造成不便;相反,采用非递归建一个二叉排序树既简单又实用。
上一篇文章: 数据结构:如何产生素数 下一篇文章: 进程退出前删除自身EXE
相关文章:

