数据结构(五)层次遍历
生活随笔
收集整理的這篇文章主要介紹了
数据结构(五)层次遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
數據結構(五)層次遍歷
// 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 //鏈式節點 {ElemType data;struct linknode* next;}LinkNode;//鏈式隊列 typedef struct {LinkNode* front, *rear;}LinkQueue;void InitQueue(LinkQueue &Q) {//帶頭節點的隊列初始化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)){//隊列為空return false;}LinkNode* p = Q.front->next;x = p->data;Q.front->next = p->next;if (p == Q.rear) //要刪除的為尾隊列{Q.rear = Q.front;}free(p);return true; }//層次遍歷 void LevelOrder(BiTree T) {LinkQueue q;BiTNode* p;//初始化隊列InitQueue(q);EnQueue(q,T); //將根節點入隊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; //如果輸入 '.' , 該樹空結點}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測試要完成如圖
總結
以上是生活随笔為你收集整理的数据结构(五)层次遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 王国保卫战4南瓜灯杰克怎么获得
- 下一篇: 你好,以前买的康佳电视,注册了通行证,忘