1. 程式人生 > >資料結構——鏈佇列實現二叉樹的層次遍歷

資料結構——鏈佇列實現二叉樹的層次遍歷

在二叉樹的遍歷這篇部落格中https://www.cnblogs.com/wkfvawl/p/9901462.html

對於二叉樹的層次遍歷我只是給出了基於C++ STL的程式碼,這裡我使用資料結構的連結串列,構建一個鏈佇列來實現。這也算是我第一次使用鏈佇列來完成某個任務,鏈佇列程式碼還是來自課本,因為之前使用C++ STL時,queue中的某些函式是有返回值的列如Q.front(),而有些卻沒有返回值像Q.push(p),Q.pop(),就連有沒有引數也是不同的,在這裡我沒有改動課本上的程式碼來適應自己的習慣,還是按照課本上來所有函式都是有返回值的,對於想要返回值的函式直接使用地址傳遞。

  1
#include<stdio.h> 2 #include<malloc.h> 3 #define TRUE 1 4 #define FALSE 0 5 #define MAX 20 6 typedef struct BTNode /*節點結構宣告*/ 7 { 8 char data ; /*節點資料*/ 9 struct BTNode *lchild; 10 struct BTNode *rchild ; /*指標*/ 11 }*BiTree; 12 typedef struct
Node///佇列中結點結構 13 { 14 BiTree data;///資料域(二叉樹結構體) 15 struct Node *next;///指標域 16 } LinkQNode; 17 typedef struct///佇列結構 18 { 19 LinkQNode *front;///隊頭指標 20 LinkQNode *rear;///隊尾指標 21 } LinkQueue; 22 void InitLinkQueue(LinkQueue *Q)///初始化列佇列 23 { 24 Q->front=(LinkQNode *)malloc(sizeof
(LinkQNode)); 25 Q->rear=Q->front;///隊頭指標和隊尾指標都指向頭結點 26 Q->front->next=NULL; 27 } 28 int IsLQEmpty(LinkQueue *Q)///判斷佇列是否為空 29 { 30 if(Q->front==Q->rear) 31 { 32 return TRUE; 33 } 34 else 35 { 36 return FALSE; 37 } 38 } 39 int EnLinkQueue(LinkQueue *Q,BiTree x) 40 { 41 LinkQNode *NewNode; 42 NewNode=(LinkQNode *)malloc(sizeof(LinkQNode));///開闢新結點 43 if(NewNode!=NULL) 44 { 45 NewNode->data=x; 46 NewNode->next=NULL; 47 Q->rear->next=NewNode;///在隊尾插入結點 48 Q->rear=NewNode;///修改隊尾指標 49 return TRUE; 50 } 51 else///溢位 52 { 53 return FALSE; 54 } 55 } 56 int DeLinkQueue(LinkQueue *Q,BiTree *x)///刪除對頭指標,並用x返回刪除的值 57 { 58 LinkQNode *p; 59 if(Q->front==Q->rear) 60 { 61 return FALSE; 62 } 63 p=Q->front->next;///p指向對頭元素 64 Q->front->next=p->next;///對頭元素p出隊 65 if(Q->rear==p)///如果佇列中只有一個元素p,則p出隊後變成空隊 66 { 67 Q->rear=Q->front; 68 } 69 *x=p->data; 70 free(p); 71 return TRUE; 72 } 73 int GetLQHead(LinkQueue *Q,BiTree *x)///獲取隊頭元素,用x返回其值 74 { 75 LinkQNode *p;///中間變數 76 if(Q->front==Q->rear) 77 { 78 return FALSE; 79 } 80 p=Q->front->next; 81 *x=p->data; 82 free(p); 83 return 1; 84 } 85 BiTree createBiTree(BiTree t) /* 先序遍歷建立二叉樹*/ 86 { 87 char s; 88 printf("\nplease input data:(exit for #)"); 89 s=getchar(); 90 if(s=='#') 91 { 92 t=NULL; 93 return t; 94 } 95 t=(BiTree)malloc(sizeof(struct BTNode)); 96 if(t==NULL) 97 { 98 printf("Memory alloc failure!"); 99 exit(0); 100 } 101 t->data=s; 102 t->lchild=createBiTree(t->lchild); /*遞迴建立左子樹*/ 103 t->rchild=createBiTree(t->rchild); /*遞迴建立右子樹*/ 104 return t; 105 } 106 107 void LevelOrder(BiTree p) 108 { 109 LinkQueue *Q; 110 Q=(LinkQueue *)malloc(sizeof(LinkQueue)); 111 InitLinkQueue(Q); 112 EnLinkQueue(Q,p); 113 while(!IsLQEmpty(Q)) 114 { 115 DeLinkQueue(Q,&p);///出佇列並取隊頭元素 116 printf("%c",p->data);//左右孩子入隊 117 if(p->lchild!=NULL) 118 { 119 EnLinkQueue(Q,p->lchild); 120 } 121 if(p->rchild!=NULL) 122 { 123 EnLinkQueue(Q,p->rchild); 124 } 125 } 126 printf("\n"); 127 } 128 int main() 129 { 130 BiTree t=NULL; 131 t=createBiTree(t); 132 printf("\n\n層次遍歷序列:"); 133 LevelOrder(t); 134 release(t); 135 return 0; 136 }