乐趣区

关于c:C语言二叉树的创建和遍历

二叉树的创立和遍历:

#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;
}
退出移动版