1. 程式人生 > >二叉樹的四種遍歷

二叉樹的四種遍歷

層序變數使用陣列作為靜態佇列簡單實現

#include <stdio.h>
#include <stdlib.h>

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

BinTree CreatBinTree(); /* 實現細節忽略 */
void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );
void LevelorderTraversal( BinTree BT );

int main()
{
    BinTree BT = CreatBinTree();
    printf("Inorder:");    InorderTraversal(BT);    printf("\n");
    printf("Preorder:");   PreorderTraversal(BT);   printf("\n");
    printf("Postorder:");  PostorderTraversal(BT);  printf("\n");
    printf("Levelorder:"); LevelorderTraversal(BT); printf("\n");
    return 0;
}
/* 你的程式碼將被嵌在這裡 */
//層序訪問
void LevelorderTraversal(BinTree BT)
{
    if (BT == NULL)
        return;
    BinTree binTree[100];   //陣列儲存數的節點,即佇列
    int head = 0, last = 0; //佇列頭和佇列尾
    binTree[last++] = BT;   //進佇列
 
    while (head < last)     
    {
      // 出佇列
        BinTree temp = binTree[head++];
        printf(" %c", temp->Data);
      // 進佇列
        if (temp->Left)     //左子樹存在
            binTree[last++] = temp->Left;
      //進佇列
        if (temp->Right)    //右子樹存在
            binTree[last++] = temp->Right;
    }
}

//前序
void PreorderTraversal(BinTree BT)
{
    if (BT == NULL)
        return;
    printf(" %c", BT->Data);
    PreorderTraversal(BT->Left);
    PreorderTraversal(BT->Right);
}
//中序遍歷
void InorderTraversal(BinTree BT)
{
    if (BT == NULL)
        return;
    InorderTraversal(BT->Left);
    printf(" %c", BT->Data);
    InorderTraversal(BT->Right);
 
}
//後序遍歷
void PostorderTraversal(BinTree BT)
{
    if (BT == NULL)
        return;
    PostorderTraversal(BT->Left);
    PostorderTraversal(BT->Right);
    printf(" %c", BT->Data);
}