扩充先序遍历创建二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27445903/article/details/82156013
#include<stdio.h>
#include<stdlib.h>

typedef struct BinNode{//初始化
    char element;
    struct BinNode *left;
    struct BinNode *right;
}BinNode,*BinTree;

void CreateBinTree(BinTree *tree){//根据所有序列创建二叉树
    char ch;
    scanf("%c",&ch);

    if(ch == '*'){
        (*tree) = NULL;
    }
    else{
        if(!(*tree = (BinTree)malloc(sizeof(BinNode)))){
            exit(-1);
        }
        (*tree)->element = ch;
        CreateBinTree(&((*tree)->left));
        CreateBinTree(&((*tree)->right));
    }
}

void Preorder(BinTree T){//先序遍历
    if(T){
        printf("%c",T->element);
        Preorder(T->left);
        Preorder(T->right);
    }
}

void Inorder(BinTree T){//中序遍历
    if(T){
        Inorder(T->left);
        printf("%c",T->element);
        Inorder(T->right);
    }
}

void Postorder(BinTree T){//后序遍历
    if(T){
        Postorder(T->left);
        Postorder(T->right);
        printf("%c",T->element);
    }
}

int main(){
    BinTree T = NULL;

    printf("请输入您要建立的二叉树的先序扩展序列(用*表示空)\n");
    CreateBinTree(&T);
    printf("构造二叉树成功!\n");
    printf("先序遍历:");
    Preorder(T);
    printf("\n中序遍历:");
    Inorder(T);
    printf("\n后序遍历:");
    Postorder(T);
    printf("\n");
}

猜你喜欢

转载自blog.csdn.net/qq_27445903/article/details/82156013