数据结构——二叉树创建及遍历

结点定义

typedef struct NODE
{
    int nValue;
    struct NODE* pLeft;
    struct NODE* pRight;
}BinaryTree;

基本创建方法:
一个结点一个结点的创建,连接。

BinaryTree* CreatBiTree()
{
    BinaryTree* pRoot=(BinaryTree*)malloc(sizeof(BinaryTree));

    pRoot->nValue=1;

    pRoot->pLeft=(BinaryTree*)malloc(sizeof(BinaryTree));
    pRoot->pLeft->nValue=2;

    pRoot->pLeft->pLeft=(BinaryTree*)malloc(sizeof(BinaryTree));
    pRoot->pLeft->pLeft->nValue=4;
    pRoot->pLeft->pLeft->pLeft=NULL;
    pRoot->pLeft->pLeft->pRight=NULL;


    pRoot->pLeft->pRight=(BinaryTree*)malloc(sizeof(BinaryTree));
    pRoot->pLeft->pRight->nValue=5;
    pRoot->pLeft->pRight->pLeft=NULL;
    pRoot->pLeft->pRight->pRight=NULL;

    pRoot->pRight=(BinaryTree*)malloc(sizeof(BinaryTree));
    pRoot->pRight->nValue=3;

    pRoot->pRight->pLeft=(BinaryTree*)malloc(sizeof(BinaryTree));
    pRoot->pRight->pLeft->nValue=6;
    pRoot->pRight->pLeft->pLeft=NULL;
    pRoot->pRight->pLeft->pRight=NULL;

    pRoot->pRight->pRight=NULL;

    return pRoot;
}

层序建立完全二叉树:

  1. 申请全部二叉树结点空间;
  2. 内存空间赋值
  3. 结点左右关系关联
BinaryTree *ArrToTree(int arr[],int nLength)
{
    if(arr == NULL || nLength <= 0)return NULL;

    //申请全部空间
    BinaryTree *pTree = NULL;
    pTree = (BinaryTree*)malloc(sizeof(BinaryTree)*nLength);

    //值拷贝
    int i;
    for(i = 0;i<nLength;i++)
    {
        pTree[i].nValue = arr[i];
        pTree[i].pLeft = NULL;
        pTree[i].pRight = NULL;
    }

    //左右关系关联
    for(i = 0;i<= nLength/2-1;i++)
    {
        if(2*i+1 < nLength)
        {
            pTree[i].pLeft = &pTree[2*i+1];
        }
        if(2*i+2 < nLength)
        {
            pTree[i].pRight = &pTree[2*i+2];
        }
    }

    return pTree;
}

前序遍历:

  1. 遍历顺序:根左右。
    递归实现代码:
void PreOderTraversal(BinaryTree* pRoot)
{
    if(pRoot==NULL)return;
    printf("%d ",pRoot->nValue);      //访问根
    PreOderTraversal(pRoot->pLeft);   //左结点
    PreOderTraversal(pRoot->pRight);  //右结点
}

中序遍历:

void InOrderTraversal(BinaryTree *pTree)
{
    if(pTree == NULL)return;

    InOrderTraversal(pTree->pLeft);
    printf("%d ",pTree->nValue);
    InOrderTraversal(pTree->pRight);
}

后序遍历

void LastOrderTraversal(BinaryTree *pTree)
{
    if(pTree == NULL)return;

    LastOrderTraversal(pTree->pLeft);
    LastOrderTraversal(pTree->pRight);
    printf("%d ",pTree->nValue);
}
posted @ 2018-09-12 16:30  DuanRui  阅读(348)  评论(0编辑  收藏  举报