只涉及二叉树的建立以及前序,先序,后序, 层序遍历;
其中当读到','时表示此节点为空。
#include<stdio.h>
#include<stdlib.h>
struct BiTNode
{
char data;
struct BiTNode *lchild, *rchild;
};
char t[51];
int cnt;
struct BiTNode *creatBiTree()
{
struct BiTNode *T;
if(t[++cnt]==',')
{
T = NULL;
}
else
{
T = (struct BiTNode*)malloc(sizeof(struct BiTNode));
T->data = t[cnt];
T->lchild = creatBiTree();
T->rchild = creatBiTree();
}
return T;
}
void visit(struct BiTNode *T)
{
if(T->data!=',')
{
printf("%c", T->data);
}
}
void PreOrder(struct BiTNode *T)
{
if(T!=NULL)
{
visit(T);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void InOrder(struct BiTNode *T)
{
if(T!=NULL)
{
InOrder(T->lchild);
visit(T);
InOrder(T->rchild);
}
}
void PostOrder(struct BiTNode *T)
{
if(T!=NULL)
{
PostOrder(T->lchild);
PostOrder(T->rchild);
visit(T);
}
}
void LevelOrder(struct node *T)
{
struct node *temp[100];
int in = 0, out = 0;
temp[in++] = T;
while(in>out)
{
if(temp[out])
{
visit(temp[out]);
temp[in++] = temp[out]->lchild;
temp[in++] = temp[out]->rchild;
}
out++;
}
}
int main()
{
while(~scanf("%s", t))
{
cnt = -1;
struct BiTNode *T;
T = creatBiTree();
preOrder(T);
printf("\n");
InOrder(T);
printf("\n");
PostOrder(T);
printf("\n");
}
return 0;
}