利用前序遍历构建二叉树(C语言)

#include<stdio.h>
#include<stdlib.h>
struct TreeNode{
    char data;
    struct TreeNode *left;
    struct TreeNode *right;
};
struct TreeNode *create_by_pre(struct TreeNode *T){/*利用前序遍历构建二叉树*/
    char ch;
    printf("ch=");
    scanf("%c",&ch);
    getchar();
    if(ch==#){
        T=NULL;
    }else{
        T=(struct TreeNode *)malloc(sizeof(struct TreeNode));
        T->data=ch;
        T->left=create_by_pre(T->left);
        T->right=create_by_pre(T->right);
    }
    return T;
}
void preOrder(struct TreeNode *T){
    if(T!=NULL){
        printf("	%c",T->data);
        preOrder(T->left);
        preOrder(T->right);
    }
}
void inOrder(struct TreeNode *T){
    if(T!=NULL){
        inOrder(T->left);
        printf("	%c",T->data);
        inOrder(T->right);
    }
}
void postOrder(struct TreeNode *T){
    if(T!=NULL){
        postOrder(T->left);
        postOrder(T->right);
        printf("	%c",T->data);
    }
}
int main(){
    struct TreeNode *T;
    T=NULL;
    T=create_by_pre(T);
    printf("前序遍历:");
    preOrder(T);
    printf("
中序遍历:");
    inOrder(T);
    printf("
后序遍历:");
    postOrder(T);
    return 0;
}
经验分享 程序员 微信小程序 职场和发展