二叉树层次遍历与链队列
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);
}
}方法二:构造与实现
//二叉树的层次遍历,使用队列实现
待续。。。
//#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); }
待续。。。
相关文章推荐
- 利用队列实现二叉树的层次遍历
- [二叉树专题]:广度优先:按层次遍历二叉树的非递归实现||使用队列实现层次遍历二叉树
- 二叉树的层次非递归遍历运用队列
- 199.leetcode Binary Tree Right Side View(medium)[层次遍历二叉树 队列]
- 数据结构 — 6.顺序队列(循环)实现二叉树层次遍历
- 二叉树前中后序遍历的递归版本和非递归版本、队列实现的层次遍历
- 二叉树层次遍历队列实现
- 数据结构 利用循环队列层次遍历一棵二叉树 递归实现
- 利用队列对二叉树进行层次遍历
- 二叉树层次遍历(借助队列实现)
- 二叉树按层次遍历--队列实现
- 利用队列进行二叉树的层次遍历
- 【C/C++】【用队列结构实现二叉树的层次遍历】
- 中序二叉树、队列实现层次遍历、中序线索二叉树的创建与遍历
- 采用队列数据结构按层次遍历二叉树
- 二叉树按层次遍历--队列实现
- 利用队列层次遍历二叉树
- 二叉树:利用两个队列层次遍历输出指定层数的叶子节点
- 二叉树按层次遍历--队列实现
- 二叉树的层次遍历 队列