您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“如何用c語言構(gòu)建一個靜態(tài)二叉樹”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“如何用c語言構(gòu)建一個靜態(tài)二叉樹”吧!
第一、樹的構(gòu)建
定義樹結(jié)構(gòu)
struct BTNode { char data; struct BTNode* pLChild; struct BTNode* pRChild; };
靜態(tài)方式創(chuàng)建一個簡單的二叉樹
struct BTNode* create_list() { struct BTNode* pA = (struct BTNode*)malloc(sizeof(BTNode)); struct BTNode* pB = (struct BTNode*)malloc(sizeof(BTNode)); struct BTNode* pC = (struct BTNode*)malloc(sizeof(BTNode)); struct BTNode* pD = (struct BTNode*)malloc(sizeof(BTNode)); struct BTNode* pE = (struct BTNode*)malloc(sizeof(BTNode)); pA->data = 'A'; pB->data = 'B'; pC->data = 'C'; pD->data = 'D'; pE->data = 'E'; pA->pLChild = pB; pA->pRChild = pC; pB->pLChild = pB->pRChild = NULL; pC->pLChild = pD; pC->pRChild = NULL; pD->pLChild = NULL; pD->pRChild = pE; pE->pLChild = pE->pRChild = NULL; return pA; }
第二、樹的三種遍歷
1. 先序遍歷
//先序輸出 void PreTravense(struct BTNode* pHead) { if (NULL!= pHead) { printf("%c", pHead->data); if (NULL!= pHead->pLChild) { PreTravense(pHead->pLChild); } if (NULL != pHead->pRChild) { PreTravense(pHead->pRChild); } } }
2. 中序遍歷
//中序輸出 void InTravense(struct BTNode* pHead) { if (NULL != pHead) { if (NULL != pHead->pLChild) { PreTravense(pHead->pLChild); } printf("%c", pHead->data); if (NULL != pHead->pRChild) { PreTravense(pHead->pRChild); } } }
3.后續(xù)遍歷
//后序輸出 void PostTravense(struct BTNode* pHead) { if (NULL != pHead) { if (NULL != pHead->pLChild) { PreTravense(pHead->pLChild); } if (NULL != pHead->pRChild) { PreTravense(pHead->pRChild); } printf("%c", pHead->data); } }
第三、最終運行測試
int main() { printf("創(chuàng)建序列\(zhòng)n"); struct BTNode* pHead = create_list(); printf("先序輸出\n"); PreTravense(pHead); printf("中序輸出\n"); InTravense(pHead); printf("后序輸出\n"); PostTravense(pHead); return 0; }
到此,相信大家對“如何用c語言構(gòu)建一個靜態(tài)二叉樹”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。