数据结构实验报告
{
int hl,hr,max; if(T){
hl=TreeDepth(T->lchild); //求左深度 hr=TreeDepth(T->rchild); //求右深度
max=hl>hr? hl:hr; //取左右深度的最大值 NodeNum=NodeNum+1; //求结点数
if(hl==0&&hr==0) leaf=leaf+1; //若左右深度为0,即为叶子。 return(max+1); }
else return(0); }
//====利用“先进先出”(FIFO)队列,按层次遍历二叉树========== void Levelorder(BinTree T) {
int front=0,rear=1;
BinTNode *cq[Max],*p; //定义结点的指针数组cq cq[1]=T; //根入队 while(front!=rear) {
front=(front+1)%NodeNum; p=cq[front]; //出队
13
数据结构实验报告
printf(\出队,输出结点的值 if(p->lchild!=NULL){ rear=(rear+1)%NodeNum;
cq[rear]=p->lchild; //左子树入队 }
if(p->rchild!=NULL){ rear=(rear+1)%NodeNum;
cq[rear]=p->rchild; //右子树入队 } } }
//==========主函数================= void main() {
BinTree root; int i,depth; printf(\
printf(\; Input preorder:\//输入完全二叉
树的先序序列,
// 用#代表虚结点,如
ABD###CE##F##
root=CreatBinTree(); //创建二叉树,返回根结点 do { //从菜单中选择遍历方式,输入序号。
14
数据结构实验报告
printf(\ printf(\ printf(\ printf(\ printf(\number\\n\
printf(\//按层次遍历之前,先选择4,求出该树的结点数。 printf(\
printf(\ scanf(\输入菜单序号(0-5) switch (i){
case 1: printf(\
Preorder(root); //先序遍历 break;
case 2: printf(\ Inorder(root); //中序遍历
break;
case 3: printf(\ Postorder(root); //后序遍历
break;
case 4: depth=TreeDepth(root); //求树的深度及叶
15
PostTreeDepth,Node number,Leaf
数据结构实验报告
子数
printf(\number=%d\
printf(\ break;
case 5: printf(\
Levelorder(root); //按层次遍历 break; default: exit(1); }
printf(\ } while(i!=0); } 执行程序 1. 先序遍历
Depth=%d
BinTree
Node
2. 中序遍历
16
相关推荐: