C语言——二叉树的创建和遍历

BEI_TIAN_XUAN

二叉树的创建和遍历:

#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define OVERFLOW -2
typedef int Status;
typedef char ElemType;
typedef struct BiNode
{
    ElemType data;
    struct BiNode* lchild, * rchild;
}BiTNode, *BiTree;
Status Create_Tree(BiTree *T);  //创建
Status PreBiTree_Traverse(BiTree T);  //构造和遍历思想:递归
Status InBiTree_Traverse(BiTree T);
Status PostBiTree_Traverse(BiTree T);
int main()
{
    BiTree T;
    int n;
    printf("请输入字符(#表示空指针):");
    Create_Tree(&T);
    printf("1.前序遍历 2.中序遍历 3.后序遍历\n");
    printf("请输入遍历方式:");
    scanf("%d", &n);
    switch (n)
    {
    case 1:PreBiTree_Traverse(T); break;
    case 2:InBiTree_Traverse(T); break;
    case 3:PostBiTree_Traverse(T); break;

    }
    return 0;
}
Status Create_Tree(BiTree *T)// 前序构造
{
    char ch;
    scanf("%c", &ch);
    if (ch == '#')     //用#代表NULL,即虚结点
    {
        *T = NULL;
    }
    else
    {
        *T = (BiTree)malloc(sizeof(BiTNode));
        if (!*T)
            exit(OVERFLOW);
        (*T)->data = ch;
        Create_Tree(&(*T)->lchild);
        Create_Tree(&(*T)->rchild);

    }
    return OK;
}
Status PreBiTree_Traverse(BiTree T)  //前序遍历
{
    if (T == NULL)
        return OVERFLOW;
    printf("二叉树的数据为:%c\n", T->data);
    PreBiTree_Traverse(T->lchild);
    PreBiTree_Traverse(T->rchild);

    return OK;
}
Status InBiTree_Traverse(BiTree T)  //中序遍历
{
    if (T == NULL)
        return OVERFLOW;
    InBiTree_Traverse(T->lchild);
    printf("二叉树的数据为:%c\n", T->data);
    InBiTree_Traverse(T->rchild);

    return OK;
}
Status PostBiTree_Traverse(BiTree T)  //后序遍历
{
    if (T == NULL)
        return OVERFLOW;
    PostBiTree_Traverse(T->lchild);
    PostBiTree_Traverse(T->rchild);
    printf("二叉树的数据为:%c\n", T->data);

    return OK;
}
阅读 68
7 声望
0 粉丝
0 条评论
7 声望
0 粉丝
宣传栏