基于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;
}