资源描述:
《二叉树的遍历算法.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、实验三二叉树遍历算法一、实验目的1.进一步理解掌握二叉树二叉链表存储结构。2.掌握二叉树遍历的递归与非递归算法。二、实验要求1.认真阅读和掌握(先序、中序、后序和层次)遍历的递归与非递归算法。2.上机调试(先序、中序、后序和层次)遍历的递归与非递归算法。3.保存和打印出程序的运行结果,并结合程序进行分析。4.上机后,认真整理源程序及其注释,完成实验报告(包括源程序、实验结果、算法分析、心得体会等)。三、实验内容先序、中序、后序遍历的递归与非递归算法和层次遍历的算法实现程序:#include"stdio.h"#i
2、nclude"stdlib.h"#include"conio.h"#definemaxsize100typedefintdatatype;typedefstructbnode{datatypedata;structbnode*lchild,*rchild;精选范本,供参考!}bnode,*btree;typedefstruct{bnode*node;intflag;}DataType;typedefstruct{DataTypedata[maxsize];inttop;}SeqStack,*PSeqStack;
3、typedefstruct{btreedata[maxsize];intfront,rear;}SeqQueue,*PSeqQueue;typedefstruct{btreedata[maxsize];inttop;}SeqStack1,*PSeqStack1;//建立一个二叉树btreecreate(){btreet;charch;scanf("%c",&ch);if(ch=='?')精选范本,供参考!t=NULL;else{t=(btree)malloc(sizeof(bnode));t->data=ch;
4、t->lchild=create();t->rchild=create();}returnt;}//先序遍历//入栈操作voidpush1(PSeqStack1s,btreesq){if(s->top==maxsize-1)printf("栈满不得入栈");else{s->top++;s->data[s->top]=sq;}}//出栈操作voidpop1(PSeqStack1s,btree*sq)精选范本,供参考!{if(s->top==-1)printf("栈空不得出栈");else{*sq=s->data[
5、s->top];s->top--;}}//先序遍历的递归算法voidPreOrder1(btreet){if(t){printf("%c",t->data);PreOrder1(t->lchild);PreOrder1(t->rchild);}}//先序遍历的非递归算法voidPreOrder2(btreet){PSeqStack1s;s=(PSeqStack1)malloc(sizeof(SeqStack1));精选范本,供参考!btreep=t;s->top=-1;while(p
6、
7、s->top!=-1){
8、if(p){printf("%c",p->data);push1(s,p);p=p->lchild;}else{pop1(s,&p);p=p->rchild;}}}//中序遍历的递归算法voidInOrder1(btreet){if(t){InOrder1(t->lchild);printf("%c",t->data);精选范本,供参考!InOrder1(t->rchild);}}//中序遍历的非递归算法voidInOrder2(btreet){PSeqStack1s;s=(PSeqStack1)malloc(
9、sizeof(SeqStack1));btreep=t;s->top=-1;while(p
10、
11、s->top!=-1){if(p){push1(s,p);p=p->lchild;}else{pop1(s,&p);printf("%c",p->data);p=p->rchild;}}精选范本,供参考!}//后序遍历的递归算法voidPostOrder1(btreet){if(t){//t=(btree)malloc(sizeof(bnode));PostOrder1(t->lchild);PostOrder1(t-
12、>rchild);printf("%c",t->data);}}//后序遍历的非递归算法//入栈操作voidpush(PSeqStacks,DataTypesq){if(s->top==maxsize-1)printf("栈满不得入栈");else{s->top++;s->data[s->top]=sq;}}精选范本,供参考!//出栈操作voidpop(PSeqStacks,DataT