广度优先遍历二叉树(BFS)-C++实现
生活随笔
收集整理的這篇文章主要介紹了
广度优先遍历二叉树(BFS)-C++实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 // 廣度優先遍歷二叉樹(BFS).cpp: 定義控制臺應用程序的入口點。2 //3 4 #include "stdafx.h"5 6 7 #include <iostream>8 #include <stdio.h>9 #include <malloc.h>10 #include <stdlib.h>11 12 using namespace std;13 14 #define QUEUE_INIT_SIZE 10015 typedef char ElemType;16 17 typedef struct BiNode18 {19 ElemType data;20 struct BiNode *lchild, *rchild;21 }BiNode, *BiPtr;22 23 typedef struct queue24 {25 int queuesize; //數組的大小26 int head, tail; //隊列的頭和尾下標27 BiPtr *q; //數組頭指針28 }Queue, *QueuePtr;29 30 int InitQueue(QueuePtr &Q)31 {32 Q->queuesize = QUEUE_INIT_SIZE;33 Q->q = (BiPtr *)malloc(sizeof(BiPtr) * Q->queuesize); //分配內存34 Q->tail = 0;//數組下標從0開始,tail始終指向隊尾元素的下一個位置35 Q->head = 0;//隊列非空時,head始終指向隊列首元素36 return 0;37 }38 39 int EnQueue(QueuePtr Q, BiPtr key)40 {41 if((Q->tail + 1) % Q->queuesize == Q->head)//取余保證,當quil=queuesize-1時,再轉回0,此時隊列沒有空間 42 {43 cout << "隊列已滿,無法再添加元素!";44 }45 else46 {47 Q->q[Q->tail] = key;48 Q->tail = (Q->tail + 1) % Q->queuesize;49 }50 return 0;51 }52 53 BiPtr DeQueue(QueuePtr Q)54 {55 BiPtr temp;56 if (Q->tail == Q->head) //判斷隊列不為空57 {58 cout << "隊列為空,無法刪除元素!";59 }60 else61 {62 temp = Q->q[Q->head];63 Q->head = (Q->head + 1) % Q->queuesize;64 }65 return temp;66 }67 68 int IsQueueEmpty(QueuePtr Q)69 {70 if (Q->head == Q->tail)//空71 return 1;72 else//非空73 return 0;74 }75 76 int IsQueueFull(QueuePtr Q)77 {78 if ((Q->tail + 1) % Q->queuesize == Q->head)79 return 1;80 else81 return 0;82 }83 84 //---------------------------------------------------85 86 int Create_BiTree(BiPtr& T)87 {88 ElemType c;89 //cout << "請輸入當前節點元素值:" << endl;90 cin >> c;91 if (c == '#') T = NULL;92 else93 {94 T = new BiNode;95 T->data = c;96 Create_BiTree(T->lchild);97 Create_BiTree(T->rchild);98 }99 return 0;
100 }
101
102 //層序遍歷
103 int LevelOrderTraverse(BiPtr T)
104 {
105 QueuePtr Q = new Queue;
106 BiPtr p = NULL;
107 InitQueue(Q);
108
109 EnQueue(Q, T);//根結點入隊
110 while (!IsQueueEmpty(Q))
111 {
112 p = DeQueue(Q);
113 cout << p->data << " ";
114 if (p->lchild)//如果p有左孩子,則左孩子入隊
115 EnQueue(Q, p->lchild);
116 if (p->rchild)//如果p有右孩子,則左孩子入隊
117 EnQueue(Q, p->rchild);
118 }
119 return 0;
120 }
121
122 int main()
123 {
124 freopen("input2.txt", "r", stdin);//從input.txt中讀取輸入數據
125 BiPtr T;
126 Create_BiTree(T);
127 LevelOrderTraverse(T);
128 fclose(stdin);
129 return 0;
130 }
?
總結
以上是生活随笔為你收集整理的广度优先遍历二叉树(BFS)-C++实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java实现清屏功能
- 下一篇: Java程序设计语言(基础篇)机械工业出