二叉树层序遍历

基于c实现二叉树的层序遍历,借助队列实现。

代码(gcc):

#include <stdlib.h>
#include <stdio.h>
typedef struct tree
{
	int nValue;
	struct tree *pLeft;
	struct tree *pRight;
}BinaryTree;

typedef struct node
{
	BinaryTree *pTree;
	struct node *pNext;
}Node;

typedef struct queue
{
	int nCount;
	Node *pHead;
	Node *pTail;
}Queue;

void Init(Queue **pQueue)
{
	
	*pQueue = (Queue*)malloc(sizeof(Queue));
	(*pQueue)->pHead = NULL;
	(*pQueue)->pTail = NULL;
	(*pQueue)->nCount = 0;
}

void Push(Queue *pQueue, BinaryTree *pTree)
{
	if(pQueue == NULL) exit(1);
	Node *pTemp = NULL;
	pTemp = (Node*)malloc(sizeof(Node));
	pTemp->pTree = pTree;
	pTemp->pNext = NULL;
	if(pQueue->pHead == NULL)
	{
		pQueue->pHead = pTemp;
	}
	else
	{
		pQueue->pTail->pNext = pTemp;
	}
	pQueue->pTail = pTemp;
	pQueue->nCount++;	
}

BinaryTree *Pop(Queue *pQueue)
{
	if(pQueue == NULL) exit(1);
	if(pQueue->nCount == 0) return NULL;
	Node *pDel = NULL;
	BinaryTree *pDelTree = NULL;
	pDel = pQueue->pHead;
	pDelTree = pQueue->pHead->pTree;
	pQueue->pHead = pQueue->pHead->pNext;
	free(pDel);
	pDel = NULL;
	pQueue->nCount--;
	if(pQueue->nCount == 0)
	{
		pQueue->pTail = NULL;
	}
	return pDelTree;
}

int IsEmpty(Queue *pQueue)
{
	if(pQueue == NULL) exit(1);
	return pQueue->nCount==0? 1:0;
}

BinaryTree *CreateBinaryTree()
{
	BinaryTree *pRoot = NULL;
	pRoot = (BinaryTree*)malloc(sizeof(BinaryTree));
	pRoot->nValue = 1;

	pRoot->pLeft = (BinaryTree*)malloc(sizeof(BinaryTree));
	pRoot->pLeft->nValue = 2;
	
	pRoot->pLeft->pLeft = (BinaryTree*)malloc(sizeof(BinaryTree));
	pRoot->pLeft->pLeft->nValue = 4;
	pRoot->pLeft->pLeft->pLeft = NULL;
	pRoot->pLeft->pLeft->pLeft = NULL;

	pRoot->pLeft->pRight = (BinaryTree*)malloc(sizeof(BinaryTree));
	pRoot->pLeft->pRight->nValue = 5;
	pRoot->pLeft->pRight->pLeft = NULL;
	pRoot->pLeft->pRight->pRight = NULL;

	pRoot->pRight = (BinaryTree*)malloc(sizeof(BinaryTree));
	pRoot->pRight->nValue = 3;
	pRoot->pRight->pLeft = NULL;
	pRoot->pRight->pRight = NULL;

	return pRoot;
}
//层序遍历
void LayerOrderTraversal(BinaryTree *pTree)
{
	if(pTree == NULL) return;
	Queue *pQueue = NULL;
	Init(&pQueue);
	Push(pQueue, pTree);
	while(!IsEmpty(pQueue))
	{
		pTree = Pop(pQueue);
		printf("%d ", pTree->nValue);
		if(pTree->pLeft != NULL)
		{
			Push(pQueue, pTree->pLeft);
		}
		if(pTree->pRight != NULL)
		{
			Push(pQueue, pTree->pRight);
		}
	}
	printf("\n");
}
int main()
{
	BinaryTree *pRoot = NULL;
	pRoot = CreateBinaryTree();
	LayerOrderTraversal(pRoot);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值