二叉树的创建,前中后序遍历,层序遍历
#include<stdio.h>
#include<stdlib.h>
typedef struct Tree
{
int data;
struct Tree *lchild;
struct Tree *rchild;
}Tree, *BitTree;
BitTree CreateLink()
{
int data;
BitTree T;
scanf("%d", &data);
if (data == -1)
return NULL;
else
{
T = (BitTree)malloc(sizeof(Tree));
T->data = data;
printf("请输入%d的左子树: ", data);
T->lchild = CreateLink();
printf("请输入%d的右子树: ", data);
T->rchild = CreateLink();
return T;
}
}
void Xianxu(BitTree T)
{
if (T == NULL)
return;
printf("%d ",T->data);
Xianxu(T->lchild);
Xianxu(T->rchild);
}
void Zhongxu(BitTree T)
{
if (T == NULL)
return;
Zhongxu(T->lchild);
printf("%d ", T->data);
Zhongxu(T->rchild);
}
void Houxu(BitTree T)
{
if (T == NULL)
return;
Houxu(T->lchild);
Houxu(T->rchild);
printf("%d ", T->data);
}
int main()
{
BitTree B;
printf("请输入第一个结点的数据:\n");
B = CreateLink();
printf("先序遍历的结果是:\n");
Xianxu(B);
printf("\n中序遍历的结果是:\n");
Zhongxu(B);
printf("\n后序遍历的结果是: \n");
Houxu(B);
return 0;
}
#include<stdio.h>
#include<malloc.h>
typedef struct BiTNode
{
char data;
struct BiTNode* lchild;
struct BiTNode* rchild;
}BiTNode, *BiTree;
typedef struct QNode
{
BiTree data;
struct QNode* next;
}QNode, *QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
void InitQueue(LinkQueue &Q)
{
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
Q.front->next = NULL;
if (Q.front)
printf("\n队列创建成功\n");
}
void EnQueue(LinkQueue& Q, BiTree B)
{
QueuePtr q = (QueuePtr)malloc(sizeof(QNode));
q->data = B;
q->next = NULL;
Q.rear->next = q;
Q.rear = q;
}
BiTree DeQueue(LinkQueue& Q, BiTree &B)
{
QueuePtr p = Q.front->next;
B = p->data;
Q.front->next = p->next;
if (Q.rear == p)
Q.front = Q.rear;
free(p);
return B;
}
bool IsEmpty(LinkQueue Q)
{
if (Q.front == Q.rear)
return true;
else
return false;
}
BiTree CreatBi()
{
char x;
BiTree B = (BiTree)malloc(sizeof(BiTNode));
scanf("%c",&x);
if (x != '.')
{
B->data = x;
B->lchild = CreatBi();
B->rchild = CreatBi();
}
else
B = NULL;
return B;
}
int main()
{
printf("请输入二叉树的结点:\n");
BiTree b = CreatBi();
LinkQueue lq;
InitQueue(lq);
EnQueue(lq,b);
BiTree temp;
while (!IsEmpty(lq))
{
temp = DeQueue(lq, b);
printf("%c",temp->data);
if (temp->lchild != NULL)
EnQueue(lq,temp->lchild);
if (temp->rchild != NULL)
EnQueue(lq, temp->rchild);
}
return 0;
}