数据结构47讲三种遍历方式的实现
#include <stdio.h>#include <stdlib.h>
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode* lchild,*rchild;
}BiTNode,*BiTree;
CreateBiTree(BiTree *T)
{
ElemType c;
scanf("%c",&c);
if(' '==c)
{
*T=NULL;
}
else
{
*T=(BiTNode*)malloc(sizeof(BiTNode));
(*T)->data=c;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
InorderTraverse0(BiTree T,int level)
{
if(T)
{
printf("%c 位于%d 层\n",T->data,level);
InorderTraverse0(T->lchild,level+1);
InorderTraverse0(T->rchild,level+1);
}
}
InorderTraverse1(BiTree T,int level)
{
if(T)
{
InorderTraverse1(T->lchild,level+1);
printf("%c 位于%d 层\n",T->data,level);
InorderTraverse1(T->rchild,level+1);
}
}
InorderTraverse2(BiTree T,int level)
{
if(T)
{
InorderTraverse2(T->lchild,level+1);
InorderTraverse2(T->rchild,level+1);
printf("%c 位于%d 层\n",T->data,level);
}
}
int main()
{
char ch;
int level=1;
BiTree T=NULL;
printf("请选择遍历方式:0为前序,1为中序,2为后序.\n");
scanf("%c",&ch);
printf("请按前序遍历的顺序输入节点:\n");
fflush(stdin);
CreateBiTree(&T);
switch(ch)
{
case '0':
InorderTraverse0(T,level);
break;
case '1':
InorderTraverse1(T,level);
break;
case '2':
InorderTraverse2(T,level);
break;
default: exit(-1);
}
return 0;
}
页:
[1]