二叉树操作的实现

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

二叉树操作的实现

实验目的与要求:

1.基础知识:掌握数据结构中二叉树的相关知识;掌握C或VC++语言中程序设计的方法.

2.参考教材相关算法,完成以下程序功能:

(1) 能够采用二叉链存储,并实现二叉树的建立;

(2)完成已建立的二叉树的三种遍历;

(3)完成二叉树中特定结点的统计,如0元素结点或叶子结点统计; (4)程序中有友好的操作设计. 实验性质:验证性(2学时)

说明:程序包含主要函数:主函数、操作界面、建树、独立的三种遍历、特定结点统计、相关注释,注意在主函数流程中体现先建树后遍历和特定结点统计的条件

#include

#include

struct node

{

char data;

struct node *lchild,*rchild;

} ;

int j=0;

int *g=&j;

void shuru(node*&t,char sn[50])

{

char ch;

ch=sn[j++];

if(ch=='@')

printf("输入的二叉树有误建树失败\n"); else if(ch=='#')t=NULL;

else

{ t=(node*)malloc(sizeof(node));

t->data=ch;

shuru(t->lchild,sn);

shuru(t->rchild,sn);

}}

void xianxu(node*&t)

{

if(t!=NULL)

{

printf("%c",t->data); xianxu(t->lchild); xianxu(t->rchild); }}

void zhongxu(node*&t) {

if(t!=NULL)

{

zhongxu(t->lchild); printf("%c",t->data); zhongxu(t->rchild); }}

void houxu(node *&t) {

if(t!=NULL)

{

houxu(t->lchild);

houxu(t->rchild);

printf("%c",t->data);

}}

int n;

int*h=&n;

void tongji(node*t)

{

if(t->lchild!=NULL||t->rchild!=NULL) {

if(t->lchild!=NULL)

tongji(t->lchild);

if(t->rchild!=NULL)

tongji(t->rchild);

}

else

n=n+1;

}

int main()

{

node *t;

t=(node*)malloc(sizeof(node));

char sn[50]={'#'};

int m,sal=1,i;

printf("----------------------------------------------------------------\n");

printf("\t本程序为建立二叉树和操作的实现\n");

printf("\t输入你要选择的操作\n");

printf("\t输入1为先序遍历二叉树\n");

printf("\t输入2为中序遍历二叉树\n");

printf("\t输入3为后序遍历二叉树\n");

printf("\t输入4为输出二叉树叶子节点的个数\n");

printf("\t输入5为结束\n");

printf("----------------------------------------------------------------\n");

do{

printf("按先序输入二叉树的元素‘#’为空以‘@’为结束标

志:\n");i=1;*g=0;

fflush(stdin);

scanf("%c",&sn[0]);

while(sn[i-1]!='@')

scanf("%c",&sn[i++]);

shuru(t,sn); } while(sn[*g-1]=='@');

while(sal)

{

printf("\t输入要选择的操作\n");

scanf("%d",&m);

if(m>5||m<1){printf("\t输入有误!请重新输入\n");}

switch(m)

{

case 1:printf("先序遍历二叉树为:");

xianxu(t);

printf("\n");break;

case 2:printf("中序序遍历二叉树为:"); zhongxu(t);

printf("\n");break;

case 3:printf("后序遍历二叉树为:"); houxu(t);

printf("\n");break;

case 4:*h=0;tongji(t);

printf("叶子节点个数为:%d\n",n); break;

case 5:printf("结束\n");

sal=0;break;

} }

return 0;

}

相关文档
最新文档