当前位置:文档之家› 二叉树的遍历及其应用实验报告

二叉树的遍历及其应用实验报告

实验报告
题目:二叉树的遍历及应用
院系:数学系
专业:数学与应用数学
学号: **********
姓名:***
一、实验名称:二叉树的遍历及应用
二、实验日期:2012年11月14日
三、实验要求:编程实现二叉树的建立并对其进行遍历
四、实验目的:
1、掌握二叉树链式存储结构的类型定义及实现;
2、掌握二叉树链式存储结构的各类基本运算方法;
3、掌握二叉树各个重要性质在解决实际问题中的应用;
4、掌握二叉树的分析方法、解决方法,从而提高实际编程能
力及程序调试能力。

五、实验内容
1、创建二叉树;
2、用递归方法实现二叉树的各种遍历。

六、程序代码
#include<stdio.h>
#include<malloc.h>
#define TRUE 1
#define FALSE 0
#define Stack_Size 50
typedef struct Node
{
char data;
struct Node *LChild;
struct Node *RChild;
}BiTNode,*BiTree;
typedef BiTree StackElementType;
typedef struct
{
StackElementType elem[Stack_Size];
int top;
}SeqStack;
//初始化
void InitStack(SeqStack *S)
{
S->top=-1;
}
//进栈
int Push(SeqStack *S,StackElementType x) { if(S->top==Stack_Size-1) return(FALSE); S->top++;
S->elem[S->top]=x;
return(TRUE);
}
//出栈
int Pop(SeqStack *S,StackElementType *x) {
if(S->top==-1)
return(FALSE);
else
{
*x=S->elem[S->top];
S->top--;
return(TRUE);
}
}
//先序遍历
void PreOrder(BiTree root)
{
if(root!=NULL)
{
printf("%c",root->data);
PreOrder(root->LChild);
PreOrder(root->RChild);
}
}
//中序遍历
void InOrder(BiTree root) { if(root!=NULL)
{ InOrder(root->LChild); printf("%c",root->data); InOrder(root->RChild);
}
}
//后序遍历
void PostOrder(BiTree root) {
if(root!=NULL)
{
PostOrder(root->LChild); PostOrder(root->RChild); printf("%c",root->data);
}
}
//创建二叉链表
void CreateBiTree(BiTree *bt)
{
char ch;
ch=getchar();
if(ch=='.') *bt=NULL;
else
{
*bt=(BiTree)malloc(sizeof(BiTNode)); (*bt)->data=ch;
CreateBiTree(&((*bt)->LChild)); CreateBiTree(&((*bt)->RChild));
}
}
//后序遍历球二叉树高度
int PostTreeDepth(BiTree bt)
{
int hl,hr,max;
if(bt!=NULL)
{
hl=PostTreeDepth(bt->LChild);
hr=PostTreeDepth(bt->RChild);
max=hl>hr?hl:hr;
return(max+1);
}
else return(0);
}
//横向打印二叉树
void PrintTree(BiTree bt,int nLayer) {
int i;
if(bt==NULL) return;
PrintTree(bt->RChild,nLayer+1);
for( i=0;i<nLayer;i++)
printf(" ");
printf("%c\n",bt->data);
PrintTree(bt->LChild,nLayer+1);
}
void main()
{
BiTree root;
printf("请输入序列:\n"); CreateBiTree(&root);
printf("输出结果为:\n");
printf("先序遍历结果:\n"); PreOrder(root);
printf("\n中序遍历结果:\n"); InOrder(root);
printf("\n后序遍历结果:\n"); PostOrder(root);
printf("\n二叉树的深度:\n");
printf("%d",PostTreeDepth(root)); printf("\n横向打印二叉树结果:\n"); PrintTree(root,5);
}
七、成果展示。

相关主题