二叉树的创建和遍历

二叉树的创建和遍历

#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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值