您的位置:首页 > 其它

二叉树层次遍历与链队列

2011-04-14 13:04 197 查看
方法一:采用STL中的queue处理
//#include <queue>
void layerOrder(BTree *tree)
{
if (tree == NULL)
return;

queue<BTree *> q;
q.push(tree);

BTree *p = NULL;
while (!q.empty())
{
p = q.front();
visit(p);

q.pop();
if (p->lchild != NULL)
q.push(p->lchild);
if (p->rchild != NULL)
q.push(p->rchild);
}
}方法二:构造与实现
//二叉树的层次遍历,使用队列实现

typedef struct _QNode
{
BiNode* data;
struct _QNode* next;
}QNode;
typedef struct _queue
{
QNode* front;
QNode* rear;
}Queue;
void InitQueue(Queue* q)
{
q->front = q->rear = (QNode*)malloc(sizeof(QNode));
q->front->next = NULL;
}


bool isQueueEmpty(Queue* q)
{
if(q->front == q->rear)
return true;
else
return false;
}


void EnQueue(Queue* q, BiNode* data)
{
QNode* pNode;
pNode = (QNode*)malloc(sizeof(QNode));
pNode->data = data;
pNode->next = NULL;
q->rear->next = pNode;
q->rear = pNode;
}


BiNode* DeQueue(Queue* q)
{
QNode* pNode;
BiNode* pData;
assert(q->front != q->rear);
pNode = q->front->next;
q->front->next = pNode->next;
if(q->rear == pNode)
{
q->rear = q->front;
}
pData = pNode->data;
free(pNode);
return pData;
}


void DestroyQueue(Queue* q)
{
while(NULL != q->front)
{
q->rear = q->front->next;
free(q->front);
q->front = q->rear;
}
}


void LayerOrderTraverse(BiNode* T)
{
Queue q;
if(NULL == T)
return;

InitQueue(&q);
EnQueue(&q,T);
while(!isQueueEmpty(&q))
{
T = DeQueue(&q);
printf("%d ",T->data);
if(T->lchild)
EnQueue(&q,T->lchild);
if(T->rchild)
EnQueue(&q,T->rchild);
}
DestroyQueue(&q);
}


待续。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struct null