[应用]数据结构 求二叉树的深度
第五次上机实验
报告
软件系统测试报告下载sgs报告如何下载关于路面塌陷情况报告535n,sgs报告怎么下载竣工报告下载
计科093班 孙浩川 200910405310
实验内容:求二叉树的深度 程序
清单
安全隐患排查清单下载最新工程量清单计量规则下载程序清单下载家私清单下载送货清单下载
:
#include
#include
#define OK 1
#define OVERFLOW -2
typedef int status;
typedef struct BiNode//二叉链表 {
char Data;
struct BiNode* lChild;
struct BiNode* rChild;
}BiNode,*pBiNode;
typedef struct SNode/*链栈的结点类型*/ {
pBiNode elem; /*栈中的元素是指向二叉链表结点的指针*/
struct SNode *next;
}SNode;
struct link //队列链表
{
struct BiNode *p;
struct link *next;
};
status CreateTree(BiNode** pTree);
int TreeHeight (BiNode* pTree);//二叉树的高度
status Visit(char Data);
void Display(BiNode* pTree,int Level);
BiNode *pRoot=NULL;
status CreateTree(BiNode** pTree) /*Input Example: abd##e##cf##g##*/
{
char ch;
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));
}
return OK;
}
int TreeHeight(BiNode* pTree)//二叉树的高度 {
int hl ,hr ; //左右子树的高度
if (pTree == NULL)
return 0 ;
else
hl = TreeHeight(pTree-> lChild);
hr = TreeHeight (pTree-> rChild);
if (hl>hr)
return (hl +1);
else
return (hr +1);
}
status Visit(char Data)
{
printf("%c ",Data);
return OK;
}
void Display(BiNode* pTree,int Level)//显示整个树
{
int i;
if(pTree==NULL) return;
Display(pTree->rChild,Level+1);
for(i=0;i=1)
{
printf("--");
}
printf("%c\n",pTree->Data);
Display(pTree->lChild,Level+1); }
void CmdList() //显示命令列表 {
printf("\n**********************************************\n");
printf(" 请选择操作: \n");
printf(" 1.求二叉树高度\n"); //二叉树高度
printf(" 0.退出程序\n"); //退出
printf("\n**********************************************\n");
}
void init()
{
printf("计科093班 孙浩川 200910405310\n");
printf("请输入二叉树各元素:(例如 abd##e##cf##g##)\n"); //例如 abd##e##cf##g##
CreateTree(&pRoot);
Display(pRoot,0);
CmdList();
}
void ReadCommand(char &c) {
do {c=getchar();}
while (c!='0'&&c!='1'); }
void Interpret(char &c)
{
switch(c)
{
case '1':
{
printf("\n二叉树高度:\n");
printf("%d\n",TreeHeight(pRoot));
CmdList();
break;
}
case '0': printf("程序结束,按任意键退出!\n");
}
}
void main() //主函数
{
char cmd;
init();
do
{
ReadCommand(cmd);
Interpret(cmd);
}
while (cmd!='0'&&cmd!='0'); }
运行截图: