二叉树的四种遍历方法.doc_第1页
二叉树的四种遍历方法.doc_第2页
二叉树的四种遍历方法.doc_第3页
二叉树的四种遍历方法.doc_第4页
全文预览已结束

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

#include #include #define MAX 100#define OVERFLOW -2typedef struct BiTree /定义二叉树节点类型char data; struct BiTree *lchild,*rchild;/定义左右孩子BitNode;BitNode *CreatBiTree()/创建二叉树char c; BitNode *T; c=getchar();if(c=0)T=NULL; elseif(!(T=(BitNode*)malloc(sizeof(BitNode)exit(OVERFLOW); T-data=c;T-lchild=CreatBiTree();T-rchild=CreatBiTree();return T;void PreOrder(BitNode *T)/非递归先序遍历BitNode *stackMAX,*p; /定义栈的容量和指针变量int top=-1;/定义栈顶指针if(T!=NULL)top+;stacktop=T;while(top-1) /栈不空时循环p=stacktop;top-;printf(%3c,p-data);if(p-rchild!=NULL)top+;stacktop=p-rchild;if(p-lchild!=NULL)top+;stacktop=p-lchild;printf(n);void InOrder(BitNode *T) /非递归中序遍历BitNode *stackMAX,*p;/定义栈的容量和指针变量int top = -1; /定义栈顶指针if (T!=NULL)p=T;while (top-1|p!=NULL)while(p!=NULL)top+;stacktop=p;p=p-lchild;if(top-1)p=stacktop;top-;printf(%3c,p-data);p=p-rchild;printf(n);void PostOrder(BitNode *T) /非递归后序遍历BitNode *stackMAX,*p; /定义栈的容量和指针变量int sign,top=-1; if(T!=NULL) dowhile(T!=NULL) top+; stacktop=T;T=T-lchild;p=NULL; sign=1; while(top!=-1&sign) T=stacktop; if(T-rchild=p) printf(%3c,T-data);top-; p=T;elseT=T-rchild;sign=0;while (top!=-1);printf(n);void LevelOrder(BitNode *T)BitNode *queueMAX,*p;int front=-1, rear=-1;queuefront+=T;/ 树根结点先进队while(front-rear+MAX)%MAX!=0)/ 当队列不为空时,出队一个结点的同时将其左右孩子进队p=queuerear+;printf(%3c, p-data);if(p-lchild!=NULL)queuefront+=p-lchild;if(p-rchild!=NULL)queuefront+=p-rchild;int main() BitNode *T; printf(please input the preorder number:n); /提示按照先序递归建立二叉树T=CreatBiTree(); printf(the nonrecursive preorder traversal result is:n); PreOrder(T); /输出非递归先序遍历printf(the nonrecursive inorder traversal result is:n);InOrder(T); /输出非递归中序遍历printf(the nonrecursive postorder traversal result is:n);PostOrder(T); /输

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论