赞
踩
借助一个辅助队列。
// biTree——树的结构体指针,seQueue——辅助队列的结构体指针 // qElemType,辅助队列中存储的元素类型,这里为树结点的指针 void levelOrder(biTree t) { seQueue seq; qElemType e; initQueue(seq); // 根节点入队 enQueue(seq, t); // 辅助队列为空时结束循环 while (seq->front != seq->rear) { // 结点出队 deQueue(seq, e); // 访问结点 cout << e->data << ' '; // 若有左子树,左子树根节点入队 if (e->lChild != NULL) enQueue(seq, e->lChild); // 若有右子树,右子树根节点入队 if (e->rChild != NULL) enQueue(seq, e->rChild); } cout << endl; }
根据上面的代码思路,需要实现两个数据结构,一个二叉树,一个队列,需要实现的功能有
/** * 树的层序建树和层序遍历 */ #include <iostream> using namespace std; const int MAXSIZE = 10; typedef char tElemType; typedef struct biTNode { tElemType data; struct biTNode *lChild, *rChild; } biTNode, *biTree; typedef biTree qElemType; typedef struct { qElemType data[MAXSIZE]; int front, rear; } seQNode, *seQueue; void initQueue(seQueue &q) { q = (seQueue) calloc(1, sizeof(seQNode)); } void enQueue(seQueue q, qElemType e) { if ((q->rear + 1) % MAXSIZE != q->front) { q->data[q->rear] = e; q->rear = (q->rear + 1) % MAXSIZE; } } void deQueue(seQueue q) { if (q->rear == q->front) return; q->front = (q->front + 1) % MAXSIZE; } void deQueue(seQueue q, qElemType &e) { if (q->rear == q->front) return; e = q->data[q->front]; q->front = (q->front + 1) % MAXSIZE; } void useLevelInitTree(biTree &t) { t = NULL; biTNode *newBTNode, *pCur; tElemType e; seQueue seq; initQueue(seq); while (scanf("%c", &e)) { if (e == '\n') break; newBTNode = (biTNode *) calloc(1, sizeof(biTNode)); newBTNode->data = e; if (t == NULL) { t = newBTNode; enQueue(seq, newBTNode); continue; } else { enQueue(seq, newBTNode); } pCur = seq->data[seq->front]; if (pCur->lChild == NULL) { pCur->lChild = newBTNode; } else if (pCur->rChild == NULL) { pCur->rChild = newBTNode; deQueue(seq); } } } void levelOrder(biTree t) { seQueue seq; qElemType e; initQueue(seq); enQueue(seq, t); while (seq->front != seq->rear) { deQueue(seq, e); cout << e->data << ' '; if (e->lChild != NULL) enQueue(seq, e->lChild); if (e->rChild != NULL) enQueue(seq, e->rChild); } cout << endl; } void inOrder(biTree t) { if (t != NULL) { inOrder(t->lChild); cout << t->data << ' '; inOrder(t->rChild); } } int main() { biTree tree; useLevelInitTree(tree); cout << "---------------------------" << endl; cout << "inOrder: "; inOrder(tree); cout << endl << "leverOrder: "; levelOrder(tree); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。