二叉树的创建和遍历
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100
typedef char Datatype;
typedef struct BiTNode
{
Datatype ch;
struct BiTNode *lchild;
struct BiTNode *rchild;
}BTN,*BTP;
typedef struct queue
{
BTP Q[MAX];
int rear, front;
}QBTP;
void iniq(QBTP *Q)
{
Q->rear = 0;
Q->front = 1;
}
BTP creat(void)
{
BTP s, root;
char ch;
QBTP Q;
iniq(&Q);
root = NULL;
printf("请输入二叉树的各个节点,@表示虚节点,#表示结束:\n");
scanf("%c", &ch);
while(ch != '#')
{
putchar(ch);
putchar('\n');
s = NULL;
if(ch != '@')
{
s = (BTN *)malloc(sizeof(BTN));
s->ch = ch;
s->lchild = NULL;
s->rchild = NULL;
}
Q.rear++;
Q.Q[Q.rear] = s;
if(Q.rear==1) root = s;
else
{
if(s&&Q.Q[Q.front])
if(Q.rear%2 == 0)
Q.Q[Q.front]->lchild = s;
else
Q.Q[Q.front]->rchild = s;
if(Q.rear%2 == 1) Q.front++;
}
scanf("%c", &ch);
}
return root;
}
void DLR(BTN *root)
{
if(root == NULL)
return;
printf("%c", root->ch);
DLR(root->lchild);
DLR(root->rchild);
}
void LDR(BTN *root)
{
if(root == NULL)
return;
LDR(root->lchild);
printf("%c", root->ch);
LDR(root->rchild);
}
void LRD(BTN *root)
{
if(root == NULL)
return;
LRD(root->lchild);
LRD(root->rchild);
printf("%c", root->ch);
}
void main()
{
BTP root;
root = creat();
printf("先序遍历:\n");
DLR(root);
printf("中序遍历:\n");
LDR(root);
printf("后序遍历:\n");
LRD(root);
}