Test05-郝斌老师-数据结构-静态链式二叉树

郝斌老师-数据结构-静态链式二叉树

Test05-郝斌老师-数据结构-静态链式二叉树_第1张图片

#include 

struct BTNode
{
    int data;
    struct BTNode *pLchild; // p是指针,L是左,child是子
    struct BTNode *pRchild;
};

struct BTNode *CreateBTree();

void PreTraverseBTree(struct BTNode *pT);
void InTraverseBTree(struct BTNode *pT);
void PostTraverseBTree(struct BTNode *pT);

int main()
{
    struct BTNode *pT = CreateBTree();
    printf("先序:\n");
    PreTraverseBTree(pT);
    printf("中序:\n");
    InTraverseBTree(pT);
    printf("后序:\n");
    PostTraverseBTree(pT);

    return 0;
}
void PreTraverseBTree(struct BTNode *pT)
{
    if (pT != NULL)
    {

        printf("%c\n", pT->data);
        if (NULL != pT->pLchild)
        {
            PreTraverseBTree(pT->pLchild);
        }
        if (NULL != pT->pRchild)
        {
            PreTraverseBTree(pT->pRchild);
        }
    }
    //先访问根节点
    //再先序访问左子树
    // pT->pLchild 代表整个左子树
    //后先序访问右子树
}
void InTraverseBTree(struct BTNode *pT)
{
    if (pT != NULL)
    {

        if (NULL != pT->pLchild)
        {
            PreTraverseBTree(pT->pLchild);
        }
        printf("%c\n", pT->data);
        if (NULL != pT->pRchild)
        {
            PreTraverseBTree(pT->pRchild);
        }
    }
}

void PostTraverseBTree(struct BTNode *pT)
{
    if (pT != NULL)
    {

        if (NULL != pT->pLchild)
        {
            PreTraverseBTree(pT->pLchild);
        }

        if (NULL != pT->pRchild)
        {
            PreTraverseBTree(pT->pRchild);
        }
        printf("%c\n", pT->data);
    }
}

//静态树
struct BTNode *CreateBTree()
{
    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 = pD->pLchild = NULL;
    pD->pRchild = pE;
    pE->pLchild = pE->pRchild = NULL;

    return pA;
}

你可能感兴趣的:(数据结构,深度优先,c语言)