二叉树遍历的的例子

二叉树遍历代码

二叉树三种遍历小例子:

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

struct BTNode * CreateBTree(void);
void PreTraverseBTree(struct BTNode * pT);
void InTraverseBTree(struct BTNode * pT);
void PostTraverseBTree(struct BTNode * pT);
struct BTNode
{
    char data;
    struct BTNode * pLchild;
    struct BTNode * pRchild;
};

int main(void)
{
    struct BTNode * pT = CreateBTree();
    //先序遍历
    //PreTraverseBTree(pT);
    //中序遍历
    //InTraverseBTree(pT);
    //后序遍历
    PostTraverseBTree(pT);
    return 0;
}

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;
}

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

//中序遍历
void InTraverseBTree(struct BTNode * pT)
{
    if(pT != NULL)
    {
        if(pT->pLchild != NULL)
        {
            //先中序遍历访问左子树
            //pT->pLchild
            InTraverseBTree(pT->pLchild);
        }
        //再访问根结点
        printf("%c\n", pT->data);
        if(pT->pRchild != NULL)
        {
            //再中序访问右子树
            InTraverseBTree(pT->pRchild);
        }
    }
}

//后序遍历
void PostTraverseBTree(struct BTNode * pT)
{
    if(pT != NULL)
    {
        if(pT->pLchild != NULL)
        {
            //先后序遍历访问左子树
            //pT->pLchild
            PostTraverseBTree(pT->pLchild);
        }
        if(pT->pRchild != NULL)
        {
            //再后序访问右子树
            PostTraverseBTree(pT->pRchild);
        }
        //最后访问根结点
        printf("%c\n", pT->data);
    }
}
    原文作者:dean_deng
    原文地址: https://blog.csdn.net/dean_deng/article/details/47904339
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞