二叉树的基本操作完整版-包含二叉树的所有操作-凡是你想要的都在里面--数据结构版.doc
文本预览下载声明
#include stdio.h
#include stdlib.h
#include string.h
#include math.h
typedef char TElemType; //定义结点数据为字符型
typedef int Status; //定义函数类型为int型
#define ERROR 0
#define OK 1
typedef struct BiTNode{ //定义结构体
TElemType data; //结点数值
struct BiTNode *lchild; //左孩子指针
struct BiTNode *rchild; //右孩子指针
struct BiTNode *next; //下一结点指针
}BiTNode, *BiTree;
Status NumJudge(char ch[20]){
//限制输入数据必须为大于零的整形
char ch1[20];
int num;
while(1){
scanf(%s,ch);
num=atoi(ch); //将字符串转换为整型
itoa(num,ch1,10); //将整型转换为字符串型
if(strcmp(ch,ch1)==0num0)break;
else{printf(请输入一个大于零的整数: );}
}
return num;
}//NumJudge
Status InitBiTree(BiTree T){
//构造空二叉树T
if(!(T=(BiTree)malloc(sizeof(BiTNode))))exit(ERROR); //若申请空间失败则退出
T-next=NULL;
printf(\n\t空二叉树构建成功!\n\n);
return OK;
}//InitBiTree
Status DestroyTree(BiTree T,BiTree t){
//销毁二叉树
if(T){
free(T);T=NULL;
printf(\t二叉树销毁成功!\n);
}
if(t){
DestroyTree(T,t-lchild);
DestroyTree(T,t-rchild);
free(t);
}
return OK;
}//DestroyTree
Status ClearBiTree(BiTree T,int sum,int i){
//清空二叉树
if(T){
ClearBiTree(T-lchild,sum,i);
ClearBiTree(T-rchild,sum,i);
free(T);
i++;
}
if(i==sum){printf(\t二叉树清空成功!\n);T=NULL;}
return OK;
}//ClearBiTree
Status CreateBiTree(BiTree T,int i,int j,TElemType ch){
//按先序次序输入二叉树中结点的值(一个字符),空格字符表示该结点为空
//构造二叉链表示的二叉树T
TElemType ch1;
int k;
char str[20];
if(i==0){printf(\n 按先序顺序建立二叉树:请按提示输入相应的数据(一个字符),若提示结点数值为空,\n 请输入空格\n\n);
printf(%5s请输入树根: , );}
if(i!=0i=j){printf(%5s请输入%c的左孩子: , ,ch);}
if(j!=0ji){printf(%5s请输入%c的右孩子: , ,ch);}
while(1){ //限制输入数据必须为字符型,否则重新输入
fflush(stdin);
for(k=0;k20;k++){
str[k]=getchar();
if(str[k]==\n)break;
}
if(k==0)printf(%5s请输入一个字符后再按Enter键: , );
if(k==1)break;
if(k1)printf(%5s您只能输入一个字符: , );
}
ch1=str[0]; //获取输入的准确字符型数据
if(ch1== ){T=NULL;return ERROR;} //输入空格则为根结点为空
if(ch1!= ){
if(!(T=(BiTree)malloc(sizeof(BiTNode)))) exit
显示全部