数据结构(五)层次遍历
生活随笔
收集整理的這篇文章主要介紹了
数据结构(五)层次遍历
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
數(shù)據(jù)結(jié)構(gòu)(五)層次遍歷
// linear_listqueue.cpp : This file contains the 'main' function. Program execution begins and ends there. //#include <iostream> #include <stdlib.h> #include <stdio.h> #define ElemType BiTree using namespace std; typedef struct BiTNode {char data;struct BiTNode* lchild, * rchild; }BitTNode, * BiTree; typedef struct linknode //鏈?zhǔn)焦?jié)點(diǎn) {ElemType data;struct linknode* next;}LinkNode;//鏈?zhǔn)疥?duì)列 typedef struct {LinkNode* front, *rear;}LinkQueue;void InitQueue(LinkQueue &Q) {//帶頭節(jié)點(diǎn)的隊(duì)列初始化Q.rear=Q.front=(LinkNode*)malloc(sizeof(LinkNode));Q.front->next = NULL; }bool IsEmpty(LinkQueue& Q) {if (Q.rear == Q.front){return true;}return false;}void EnQueue(LinkQueue& Q, ElemType x) {LinkNode* s= (LinkNode*)malloc(sizeof(LinkNode));s->data = x;s->next = Q.rear->next;Q.rear->next = s;Q.rear = s;}bool DeQueue(LinkQueue& Q, ElemType &x) {if (IsEmpty(Q)){//隊(duì)列為空return false;}LinkNode* p = Q.front->next;x = p->data;Q.front->next = p->next;if (p == Q.rear) //要?jiǎng)h除的為尾隊(duì)列{Q.rear = Q.front;}free(p);return true; }//層次遍歷 void LevelOrder(BiTree T) {LinkQueue q;BiTNode* p;//初始化隊(duì)列InitQueue(q);EnQueue(q,T); //將根節(jié)點(diǎn)入隊(duì)while (!IsEmpty(q)){DeQueue(q,p);printf("%c\t",p->data);if (p->lchild != NULL){EnQueue(q,p->lchild);}if (p->rchild != NULL){EnQueue(q, p->rchild);}}} bool createBiTree(BiTree& T) {char ch;cin >> ch;if (ch == '.'){T = NULL; //如果輸入 '.' , 該樹空結(jié)點(diǎn)}else{T = (BitTNode*)malloc(sizeof(BitTNode));if (T == NULL){printf("tree error!\n");exit(1);}T->data = ch;createBiTree(T->lchild);createBiTree(T->rchild);}return true; }int main() {//int x;//LinkQueue Q;//InitQueue(Q);//EnQueue(Q, 5);//EnQueue(Q, 7);//EnQueue(Q, 9);//DeQueue(Q, x);//LinkNode* p = Q.front->next;//while (p != NULL)//{// printf("%d\n",p->data);// p = p->next;//}BiTree T;createBiTree(T);LevelOrder(T);}// Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu// Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file測(cè)試要完成如圖
總結(jié)
以上是生活随笔為你收集整理的数据结构(五)层次遍历的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 王国保卫战4南瓜灯杰克怎么获得
- 下一篇: Qt+OpenCV打开视频文件并在窗口界