用先序递归过程建立二叉树

用先序递归过程建立二叉树 (存储结构:二叉链表)
输入数据按先序遍历所得序列输入,当某结点左子树或右子树为空时,输入‘*’号,如输入abc**d**e**得到的二叉树如下:

  a
 b e
c d

代码如下:

#include <cstdio>
#include <cstdlib>
#include <cstring>

typedef struct tree{//二叉树结构
    char data;
    struct tree *lc,*rc;
}BitNode,*BitTree;

typedef struct queu{//先序序列存储队列,包含'*'
    char data;
    struct queu *next;
}QueueNode,*Queue;
Queue head = NULL,rear = head;

void enqueue(Queue &head, Queue &rear,char ch){//入队
    Queue p = (Queue)malloc(sizeof(QueueNode));
    p->data = ch;
    p->next = NULL;
    if(head == NULL){
        head = p;
        rear = p;
    }
    else{
        rear->next = p;
        rear = p;
    }
    return ;
}

Queue Del(Queue head){//删除节点操作
    Queue temp = head -> next;
    free(head);
    return temp;
}

char dequeue(Queue &head){//出队
    if(head == NULL)
        return NULL;
    char ch = head->data;
    head = Del(head);
    return ch;
}

void BuildTree(BitTree &root){//根据带'*'先序序列建树
    char ch = dequeue(head);
    if(ch == '*' || ch == '')//遇到'*',直接返回
        return;
    root = (BitTree)malloc(sizeof(BitNode));
    root->data = ch;
    root->lc = NULL;
    root->rc = NULL;

    BuildTree(root->lc);
    BuildTree(root->rc);
    return ;
}

void PreOrder(BitTree root){//先序遍历输出
    printf("%c",root->data);
    if(root->lc)
        PreOrder(root->lc);
    if(root->rc)
        PreOrder(root->rc);
}

void MidOrder(BitTree root){//中序遍历输出
    if(root->lc)
        PreOrder(root->lc);
    printf("%c",root->data);
    if(root->rc)
        PreOrder(root->rc);
}

void AftOrder(BitTree root){//后续遍历输出
    if(root->lc)
        AftOrder(root->lc);
    if(root->rc)
        AftOrder(root->rc);
    printf("%c",root->data);
}

int main(){
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    char ch[10000];

    scanf("%s",ch);
    for(int i = 0;ch[i] != '';i++)
        enqueue(head,rear,ch[i]);
    BitTree root;
    BuildTree(root);
    PreOrder(root);
    printf("
");
    MidOrder(root);
    printf("
");
    AftOrder(root);
    printf("
");
    return 0;
}
原文地址:https://www.cnblogs.com/sean10/p/5043598.html