回到顶部

网站工具

管 理
flash插件下载
首页 概论 线性表 栈和队列 多维数组 广义表 排序 查找 文件
【题目】请设计一个算法,把二叉树的叶子结点按从左到右的顺序连成一个单链表。二叉树
按lchild - rchild 的方式存储,链接时用叶子结点的rchild 域存放指针。

【来源】长沙铁道学院99年第四(3)题(8’)

【解答】
#include <stdio.h>
#include <alloc.h>
#include <string.h>
#include <ctype.h>
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;} // 输出该链表
}


【分析】建一个一般的二叉树如果采用递归的话,将对调用该二叉树造成不便;相反,采用
非递归建一个二叉排序树既简单又实用。