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

#include
#include
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("\t%c",T->data);
        preOrder(T->left);
        preOrder(T->right);
    }
}
void inOrder(struct TreeNode *T){
    if(T!=NULL){
        inOrder(T->left);
        printf("\t%c",T->data);
        inOrder(T->right);
    }
}
void postOrder(struct TreeNode *T){
    if(T!=NULL){
        postOrder(T->left);
        postOrder(T->right);
        printf("\t%c",T->data);
    }
}
int main(){
    struct TreeNode *T;
    T=NULL;
    T=create_by_pre(T);
    printf("前序遍历:");
    preOrder(T);
    printf("\n中序遍历:");
    inOrder(T);
    printf("\n后序遍历:");
    postOrder(T);
    return 0;
}

利用前序遍历构建二叉树(C语言)_第1张图片

 利用前序遍历构建二叉树(C语言)_第2张图片

 

你可能感兴趣的:(树,数据结构,c语言)