// 二叉树.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "stdio.h"
#include "windows.h"
#include <stdlib.h>
typedef struct BitTree{
int data; //存放数据域
struct BitTree * lchild; //遍历左子树指针
struct BitTree * rchild; //遍历右子树指针
}BitTree;
typedef struct Queue
{
BitTree data;
struct Queue *next;
}Queue;
typedef struct LinkQueue
{
Queue *front;
Queue *rear;
int size;
}LinkQueue;
//初始化队列
void InitQueue(LinkQueue *Q )
{
Queue * pHead = (Queue *)malloc(sizeof(Queue));
Q->front = pHead;
Q->rear = pHead;
Q->front->next = NULL;
Q->size = 0;
}
//判断队列是否为空
bool EmptyQueue(LinkQueue *Q)
{
if (Q->rear == Q->front)
{
return true;
}
else return false;
}
//入队
void EnQueue(LinkQueue *Q, BitTree e)
{
Queue *pNewNode = (Queue *)malloc(sizeof(Queue));
pNewNode->data = e; //将数据元素赋值给结点数据域
Q->rear->next = pNewNode; //将原来队列的队尾指针指向新的结点
Q->rear = pNewNode; //将队尾指针指向新结点
Q->rear->next = NULL;
}
//出队
void DeQueue(LinkQueue *Q,BitTree *e)
{
//Queue *e = (Queue*)malloc(sizeof(Queue));
if (EmptyQueue(Q))
{
printf("队列为空");
return;
}
Queue *p = Q->front->next;
*e = p->data;
Q->front->next = p->next;
if (Q->rear == p)
{
Q->rear = Q->front;
}
free(p);
}
//创建二叉树
BitTree *CreateBitTree()
{
int data;
int temp;
BitTree *T = NULL;
scanf("%d", &data); //输入数据
temp = getchar(); //过滤空格
if (data == -1)
{
return NULL;
}
else
{
T = (BitTree*)malloc(sizeof(BitTree));
T->data = data;
printf("请输入%d的左子树:", data);
T->lchild= CreateBitTree();
printf("请输入%d的右子树:", data);
T->rchild = CreateBitTree();
return T;
}
}
//前序遍历
void PreOrderTraverse(BitTree *T)
{
if (T)
{
printf("%d ", T->data);
PreOrderTraverse(T->lchild);
PreOrderTraverse(T->rchild);
}
}
//中序遍历
void InOrderTraverse(BitTree * T)
{
if (T)
{
InOrderTraverse(T->lchild);
printf("%d ", T->data);
InOrderTraverse(T->rchild);
}
}
//后序遍历
void LastOrderTraverse(BitTree * T)
{
if (T)
{
LastOrderTraverse(T->lchild);
LastOrderTraverse(T->rchild);
printf("%d ", T->data);
}
}
//层次遍历
void FloorOrderTraverse(BitTree * T, LinkQueue *Q)
{
BitTree *e = (BitTree*)malloc(sizeof(BitTree));
if (T)
{
EnQueue(Q, *T); //根结点进队列
}
while (EmptyQueue(Q) == false)
{
DeQueue(Q,e);
printf("%d ", (e->data));
if (e->lchild != NULL)
{
EnQueue(Q, *(e->lchild));
}
if (e->rchild != NULL)
{
EnQueue(Q, *(e->rchild));
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
BitTree *s = NULL;
LinkQueue *Q = (LinkQueue*)malloc(sizeof(LinkQueue));
InitQueue(Q);
s = CreateBitTree();
printf("先序遍历结果: \n");
PreOrderTraverse(s); // 先序遍历二叉树
printf("\n\n");
printf("中序遍历结果: \n");
InOrderTraverse(s); // 中序遍历二叉树
printf("\n\n");
printf("后序遍历结果: \n");
LastOrderTraverse(s); // 中序遍历二叉树
printf("\n\n");
printf("层序遍历结果: \n");
FloorOrderTraverse(s, Q);
printf("\n\n");
system("pause");
return 0;
}
【数据结构】二叉树先序遍历,中序遍历,后序遍历,层次遍历
最新推荐文章于 2023-02-28 21:39:17 发布