数据结构-求二叉树的深度

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

第五次上机实验报告计科093班孙浩川200910405310实验内容:求二叉树的深度程序清单:#includestdio.h#includestdlib.h#defineOK1#defineOVERFLOW-2typedefintstatus;typedefstructBiNode//二叉链表{charData;structBiNode*lChild;structBiNode*rChild;}BiNode,*pBiNode;typedefstructSNode/*链栈的结点类型*/{pBiNodeelem;/*栈中的元素是指向二叉链表结点的指针*/structSNode*next;}SNode;structlink//队列链表{structBiNode*p;structlink*next;};statusCreateTree(BiNode**pTree);intTreeHeight(BiNode*pTree);//二叉树的高度statusVisit(charData);voidDisplay(BiNode*pTree,intLevel);BiNode*pRoot=NULL;statusCreateTree(BiNode**pTree)/*InputExample:abd##e##cf##g##*/{charch;scanf(%c,&ch);if(ch=='#'){(*pTree)=NULL;}else{if(!((*pTree)=(BiNode*)malloc(sizeof(BiNode)))){exit(OVERFLOW);}(*pTree)-Data=ch;CreateTree(&((*pTree)-lChild));CreateTree(&((*pTree)-rChild));}returnOK;}intTreeHeight(BiNode*pTree)//二叉树的高度{inthl,hr;//左右子树的高度if(pTree==NULL)return0;elsehl=TreeHeight(pTree-lChild);hr=TreeHeight(pTree-rChild);if(hlhr)return(hl+1);elsereturn(hr+1);}statusVisit(charData){printf(%c,Data);returnOK;}voidDisplay(BiNode*pTree,intLevel)//显示整个树{inti;if(pTree==NULL)return;Display(pTree-rChild,Level+1);for(i=0;iLevel-1;i++){printf();}if(Level=1){printf(--);}printf(%c\n,pTree-Data);Display(pTree-lChild,Level+1);}voidCmdList()//显示命令列表{printf(\n**********************************************\n);printf(请选择操作:\n);printf(1.求二叉树高度\n);//二叉树高度printf(0.退出程序\n);//退出printf(\n**********************************************\n);}voidinit(){printf(计科093班孙浩川200910405310\n);printf(请输入二叉树各元素:(例如abd##e##cf##g##)\n);//例如abd##e##cf##g##CreateTree(&pRoot);Display(pRoot,0);CmdList();}voidReadCommand(char&c){do{c=getchar();}while(c!='0'&&c!='1');}voidInterpret(char&c){switch(c){case'1':{printf(\n二叉树高度:\n);printf(%d\n,TreeHeight(pRoot));CmdList();break;}case'0':printf(程序结束,按任意键退出!\n);}}voidmain()//主函数{charcmd;init();do{ReadCommand(cmd);Interpret(cmd);}while(cmd!='0'&&cmd!='0');}运行截图:

1 / 4
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功