1. 程式人生 > >實驗四 二叉樹基本操作的實現

實驗四 二叉樹基本操作的實現

實現鏈式儲存建立,遞迴先序 中序 後序遍歷,葉子結點數,數的結點總數,交換左右子樹

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int cnt;
//結點宣告,資料域 左子樹 右子樹
typedef struct BiNode
{
    char data;
    struct BiNode *lchild,*rchild;
}BiNode,*BiTree;
//建立二叉樹
/*void Init(BiTree T)
{
    T=NULL;
    return;
}*/
BiTree Creat_BiTree()
{
    BiTree T;
    char ch;
    scanf("%c",&ch);
    if(ch=='#')
        T=NULL;
    else
    {
        T=(BiNode *)malloc(sizeof(BiNode));//為結點申請一個sizeof(BiNode)大小的空間
        T->data=ch;
        T->lchild=Creat_BiTree();//建立左子樹
        T->rchild=Creat_BiTree();//建立右子樹
    }
    return T;
}
//先序遍歷
void Pre_order(BiTree T)
{
    if(T)
    {
        printf("%c",T->data);
        Pre_order(T->lchild);
        Pre_order(T->rchild);
    }
}
//中序遍歷
void In_order(BiTree T)
{
    if(T)
    {
        In_order(T->lchild);
        printf("%c",T->data);
        In_order(T->rchild);
    }
}
//後序遍歷
void Post_order(BiTree T)
{
    if(T)
    {
        Post_order(T->lchild);
        Post_order(T->rchild);
        printf("%c",T->data);
    }
}
//二叉樹葉子總結點數
int Num_BiTree(BiTree T)
{
    if(T==NULL)
        return 0;
    if(T->lchild==NULL&&T->rchild==NULL)
    {
        cnt++;
    }
    return Num_BiTree(T->lchild)+Num_BiTree(T->rchild)+1;
}
//交換左右子樹
void Change_child(BiTree T)
{
    BiTree temp;
    if(T==NULL)
        return ;
    else
    {
        Change_child(T->lchild);
        Change_child(T->rchild);
        temp=T->lchild;
        T->lchild=T->rchild;
        T->rchild=temp;
    }
}
int main()
{
    BiTree T;
    printf("********二叉樹的基本操作********\n\n");
    printf("\n建立鏈式儲存二叉樹:\n");
    T=Creat_BiTree();
    /******三種遍歷方式******/
    printf("\n輸出先序遍歷二叉樹:\n");
    Pre_order(T);
    printf("\n輸出中序遍歷二叉樹:\n");
    In_order(T);
    printf("\n輸出後序遍歷二叉樹:\n");
    Post_order(T);
    cnt=0;
    int ans=Num_BiTree(T);
    printf("\n\n輸出二叉樹葉子總結點和葉子結點數:\n");
    printf("%d %d\n",ans,cnt);
    Change_child(T);
    printf("\n交換左右子樹後輸出遍歷結果\n");
    /******三種遍歷方式******/
    printf("\n輸出先序遍歷二叉樹:\n");
    Pre_order(T);
    printf("\n輸出中序遍歷二叉樹:\n");
    In_order(T);
    printf("\n輸出後序遍歷二叉樹:\n");
    Post_order(T);
    printf("\n\nOK!");
    return 0;
}