二叉树的建立和遍历
#include<stdio.h>
#include<stdlib.h>
typedef char ElemType;
typedef struct BiNode
{
char date;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
//create 前序遍历
CreateBiTree(BiTree *T)
{
char c;
scanf("%c",&c);
if(' '==c)
{
*T=NULL;
}
else
{
*T=(BiTNode *)malloc(sizeof(BiTNode));
(*T)->date=c;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
//
visit(char c,int level)
{
printf("%c 位于第%d层\n",c,level);
}
//遍历二叉树
PreOrderTraverse(BiTree T,int level)
{
if(T)
{
visit(T->date,level);
PreOrderTraverse(T->lchild,level+1);
PreOrderTraverse(T->rchild,level+1);
}
}
int main()
{
int level=1;
BiTree T = NULL;
CreateBiTree(&T);
PreOrderTraverse(T,level);
return 0;
}