C语言 -- 数据结构 --- 二叉树的遍历

124 阅读2分钟

二叉树的创建,前中后序遍历,层序遍历

#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);
    //  输入-1时,代表该节点不存在数据
    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() 
{
	//1.创建树
	printf("请输入二叉树的结点:\n");
	BiTree b = CreatBi();
	//2.初始化辅助队列
	LinkQueue lq;
	InitQueue(lq);
	//3.头结点入队
	EnQueue(lq,b);
	BiTree temp;
	//4.遍历
	while (!IsEmpty(lq))
	{
	//4.1 头结点出队
		temp = DeQueue(lq, b);
	//4.2 访问出队结点
		printf("%c",temp->data);
	//4.3 左子树根节点入队
		if (temp->lchild != NULL)
			EnQueue(lq,temp->lchild);
	//4.4 右子树根节点入队
		if (temp->rchild != NULL)
			EnQueue(lq, temp->rchild);	
	}

	return 0;
}