欢迎来到天天文库
浏览记录
ID:34434920
大小:33.50 KB
页数:3页
时间:2019-03-06
《代码:天津理工大学数据结构实验——二叉树的创建与遍历》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、/*Note:YourchoiceisCIDE*/#include#include#includetypedefstructBTNode{chardata;structBTNode*pLchild;structBTNode*pRchild;}BTNode;BTNode*CreateBTree();voidPreTraverseBTree(BTNode*);voidInTraverseBTree(BTNode*);voidPostTraverseBTree(BTNode*);voidDestroyBiTree(BTNod
2、e*);voidmain(){BTNode*pT=NULL;chara;loop:printf("1…建立二叉树");printf("2…前序遍历二叉树");printf("3…中序遍历二叉树");printf("4…后序遍历二叉树");printf("0…结束");a=getch();printf("");if(a=='1'){printf("先序输入二叉树:");pT=CreateBTree();printf("");printf("");gotoloop;}if(a=='2'){PreTraverseBTree(pT);printf("
3、n");printf("");gotoloop;}elseif(a=='3'){InTraverseBTree(pT);printf("");printf("");gotoloop;}elseif(a=='4'){PostTraverseBTree(pT);printf("");printf("");gotoloop;}elseif(a=='0')exit(-1);else{printf("输入错误,请重新输入!");gotoloop;}printf("");}BTNode*CreateBTree(){BTNode*pT;charch;//scan
4、f("%c",&ch);ch=getche();if(ch=='#')pT=NULL;else{pT=(BTNode*)malloc(sizeof(BTNode));pT->data=ch;pT->pLchild=CreateBTree();pT->pRchild=CreateBTree();}returnpT;}voidPreTraverseBTree(BTNode*pT){if(pT!=NULL){printf("%c",pT->data);if(pT->pLchild!=NULL)PreTraverseBTree(pT->pLchild);if(pT->pRchild!
5、=NULL)PreTraverseBTree(pT->pRchild);}}voidInTraverseBTree(BTNode*pT){if(pT!=NULL){if(pT->pLchild!=NULL)InTraverseBTree(pT->pLchild);printf("%c",pT->data);if(pT->pRchild!=NULL)InTraverseBTree(pT->pRchild);}}voidPostTraverseBTree(BTNode*pT){if(pT!=NULL){if(pT->pLchild!=NULL)PostTraverseBTree(
6、pT->pLchild);if(pT->pRchild!=NULL)PostTraverseBTree(pT->pRchild);printf("%c",pT->data);}}voidDestroyBiTree(BTNode*pT){if(pT!=NULL){if(pT->pLchild!=NULL)DestroyBiTree(pT->pLchild);if(pT->pRchild!=NULL)DestroyBiTree(pT->pRchild);free(pT);pT=NULL;}}
此文档下载收益归作者所有