数据结构实验报告——中序遍历二叉树_二叉树的遍历实验报告
数据结构实验报告——中序遍历二叉树由刀豆文库小编整理,希望给你工作、学习、生活带来方便,猜你可能喜欢“二叉树的遍历实验报告”。
班级:380911班
学号:57000211 姓名:徐敏
实验报告
一,实验目的:
·掌握二叉树的链式存储结构; ·掌握构造二叉树的方法;
·加深对二叉树的中序遍历的理解; 二,实验方法:
·用递归调用算法中序遍历二叉树。三,实验步骤:
·通过链式存储建立一颗二叉树。
·设计一个算法实现中序遍历二叉树。四,具体实验步骤:
#include #include #define LEFT 0 #define RIGHT 1 #define TRUE 1 #define FALSE 0
typedef struct _BTNODE{ char c;struct _BTNODE *lchild;struct _BTNODE *rchild;}BTNODE,*PBTNODE;
void PrintBTree(PBTNODE p,int depth);void ConstructBTree(PBTNODE p);void InorderTraverse(PBTNODE p);
void main(){ PBTNODE p;p=(PBTNODE)calloc(1,sizeof(BTNODE));printf(“Input the data:”);ConstructBTree(p);PrintBTree(p,0);printf(“Now InorderTraverse:”);InorderTraverse(p);printf(“nPre any key to continue...”);getchar();}
void PrintBTree(PBTNODE p,int depth){
班级:380911班
学号:57000211 姓名:徐敏
int i;if(p==NULL){
return;}else{ for(i=0;i
printf(“--”);} printf(“>”);
printf(“%cn”,p->c);
PrintBTree(p->lchild,depth+1);
PrintBTree(p->rchild,depth+1);} }
void ConstructBTree(PBTNODE p){ int side;char c;side=LEFT;while(TRUE){
scanf(“%c”,&c);
if(c=='n'){
//printf(“EOFn”);
return;
} // printf(“%dn”,c);
switch(c){
case '|':
break;
case')':
return;
case',':
side=RIGHT;
break;
case'(':
if(side==LEFT){
if(p->lchild==NULL){
p->lchild=(PBTNODE)calloc(1,sizeof(BTNODE));
}
ConstructBTree(p->lchild);
}else{
if(p->rchild==NULL){
p->rchild=(PBTNODE)calloc(1,sizeof(BTNODE));
}
班级:380911班
学号:57000211 姓名:徐敏
ConstructBTree(p->rchild);
}
break;
default:
if(side==LEFT){
p->lchild=(PBTNODE)calloc(1,sizeof(BTNODE));
p->lchild->c=c;
}else{
p->rchild=(PBTNODE)calloc(1,sizeof(BTNODE));
p->rchild->c=c;
}
} } }
void InorderTraverse(PBTNODE p){ if(p==NULL){
return;}else{
InorderTraverse(p->lchild);
printf(“[%c] ”,p->c);
InorderTraverse(p->rchild);} return;} 五,实验过程:
·输出:Input the date;
·输入:1(2(3,4),5(6,7));
·输出:Now InorderTraverse:【3】【2】【4】【1】【6】【5】【7】;六,上机实验体会:
·体会到熟练掌握各种程序算法的重要性;
·通过上机练习,充分理解了链式建立二叉树的算法;
·形象的了解二叉树的结构,能够熟练的进行先序,中序,后序遍历二叉树。