1. 程式人生 > >C_數據結構_鏈式二叉樹

C_數據結構_鏈式二叉樹

數據結構 nod creat all 二叉樹 \n class oid int

# include <stdio.h>
# include <malloc.h>

struct BTNode
{
    int data;
    struct BTNode * pLchild; // p 是指針   L 是左   child 是孩子
    struct BTNode * pRchild; // 表示右孩子
};

struct BTNode * CreateBTree(void); //靜態創建二叉樹
void PreTraverseBTree(struct BTNode * pT); //先序遍歷
void InTraverseBTree(struct
BTNode * pT); //中序遍歷 void PostTraverseBTree(struct BTNode * pT); //後續遍歷 int main(void) { BTNode pT = CreateBTree(); //這裏不能加 void PreTraverseBTree(pT); //先序遍歷 InTraverseBTree(pT); //中序遍歷 PostTraverseBTree(pT); //後續遍歷 return 0; } void PostTraverseBTree(struct BTNode * pT) //
後續遍歷 { if (pT != NULL) { if (NULL != pT->pLchild) { PostTraverseBTree(pT->pLchild); // pT->pLchild可以代表整個左子樹 } if (NULL != pT->pRchild) { PostTraverseBTree(pT->pRchild); } printf(
"%c\n", pT->data); } } void InTraverseBTree(struct BTNode * pT) //中序遍歷 { if (pT != NULL) { if (NULL != pT->pLchild) { InTraverseBTree(pT->pLchild); // pT->pLchild可以代表整個左子樹 } printf("%c\n", pT->data); if (NULL != pT->pRchild) { InTraverseBTree(pT->pRchild); } } } void PreTraverseBTree(struct BTNode * pT) //先序遍歷 { if (pT != NULL) { printf("%c\n", pT->data); if (NULL != pT->pLchild) { PreTraverseBTree(pT->pLchild); // pT->pLchild可以代表整個左子樹 } if (NULL != pT->pRchild) { PreTraverseBTree(pT->pRchild); } } // if 判斷不能省略 /* //偽算法 先訪問跟節點 再先序訪問左子樹 在先序訪問右子樹 */ } struct BTNode * CreateBTree(void) { struct BTNode pA = (struct BTNode *)malloc(sizeof(struct BTNode)); struct BTNode pB = (struct BTNode *)malloc(sizeof(struct BTNode)); struct BTNode pC = (struct BTNode *)malloc(sizeof(struct BTNode)); struct BTNode pD = (struct BTNode *)malloc(sizeof(struct BTNode)); struct BTNode pE = (struct BTNode *)malloc(sizeof(struct 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; }

C_數據結構_鏈式二叉樹