c語言_構(gòu)建一個(gè)靜態(tài)二叉樹實(shí)現(xiàn)方法
更新時(shí)間:2017年05月28日 11:11:57 投稿:jingxian
下面小編就為大家?guī)硪黄猚語言_構(gòu)建一個(gè)靜態(tài)二叉樹實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
第一、樹的構(gòu)建
定義樹結(jié)構(gòu)
struct BTNode {
char data;
struct BTNode* pLChild;
struct BTNode* pRChild;
};
靜態(tài)方式創(chuàng)建一個(gè)簡單的二叉樹
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);
}
}
第三、最終運(yùn)行測試
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)建一個(gè)靜態(tài)二叉樹實(shí)現(xiàn)方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
C++ LeetCode1780判斷數(shù)字是否可以表示成三的冪的和
這篇文章主要為大家介紹了C++ LeetCode1780判斷數(shù)字是否可以表示成三的冪的和題解示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
最新C/C++中的new和delete的實(shí)現(xiàn)過程小結(jié)
這篇文章主要介紹了C/C++中的new和delete的實(shí)現(xiàn)過程,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
C++使用循環(huán)計(jì)算標(biāo)準(zhǔn)差的代碼實(shí)現(xiàn)
在C++中,計(jì)算標(biāo)準(zhǔn)差可以使用循環(huán)來實(shí)現(xiàn),本文給大家介紹了一個(gè)示例代碼,演示了如何使用循環(huán)計(jì)算標(biāo)準(zhǔn)差,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2023-12-12

