一.实验任务: 二叉树的遍历:分别以顺序存储结构和二叉链表作存储结构,试编写前序、中序、后序及层次顺序遍历二叉树的算法。
二.实验任务的子任务: 本人设计以二叉链表作存储结构,编写前序、中序、后序及层次顺序遍历二叉树的算法。
三.算法分析(如图):文字或流程图或画图说明都可 1.假设输入的数据即为一个二叉链结构。 2.再分别按前序,中序,后序及层次顺序遍历二叉树结构。 3.最后按实验顺序将结果进行显示。
四.源代码: #include <stdio.h> #include<malloc.h> #include<stdio.h> #define M 10
typedefintDataType;/*元素的数据类型*/ typedefstructnode { DataTypedata; structnode *lchild,*rchild; }BitTNode,*BiTree;
intfront=0,rear=0; BitTNode *que[10]; BitTNode *creat() { BitTNode *t; DataTypex; scanf("%d",&x); if(x==0) t=NULL; else{ t=(BitTNode *)malloc(sizeof(BitTNode)); t->data=x; t->lchild=creat(); t->rchild=creat(); } return(t); }/*creat*/ /* 前序遍历二叉树t */ voidpreorder(BiTreet) { if(t!=NULL) { printf("%4d",t->data); preorder(t->lchild); preorder(t->rchild); } } /* 中序遍历二叉树t */ voidinorder(BiTreet) { if(t!=NULL) { inorder(t->lchild); printf("%4d",t->data); inorder(t->rchild); } } /* 后序遍历二叉树t */ voidpostorder(BiTreet) { if(t!=NULL) { postorder(t->lchild); postorder(t->rchild); printf("%4d",t->data); } } voidenqueue(BitTNode *t) { if (front!=(rear+1)%M) { rear=(rear+1)%M; que[rear]=t; } }/*enqueue*/
BitTNode * delqueue() { if(front==rear)returnNULL; { front=(front+1)%M; return (que[front]); } }/*delqueue*/
/* 按层次遍历二叉树t */ voidlevorder(BiTreet) { BitTNode *p; if(t!=NULL) { enqueue(t); while (front!=rear) { p=delqueue(); printf("%4d",p->data); if(p->lchild!=NULL) enqueue(p->lchild); if(p->rchild!=NULL) enqueue(p->rchild); } } }/* levorder */ voidmain() { BitTNode *root; root=creat(); printf("\n按先序遍历次序生成的二叉树"); printf("\n前序遍历二叉树"); preorder(root); printf("\n中序遍历二叉树"); inorder(root); printf("\n后序遍历二叉树"); postorder(root); printf("\n层次顺序遍历二叉树"); levorder(root); } 运行结果:
|
实验结论: 通过本实验我们可以进一步了解,二叉树的创建,前、后、中序遍历,以及二叉树的一些基本性质等操作。对递归调用有了更进一步的理解。
|
设计性实验一 二叉树的遍历
最新推荐文章于 2022-08-18 14:44:05 发布