10

根据前序遍历和中序遍历建立二叉树,并后序遍历输出以及交换左右子树后输出,请修改下面代码

#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define maxsize 50

typedef struct Bnode
{
    char data;
    struct Bnode *Lchild, *Rchild;
}BTnode, *BTptr;

BTptr CreateBT(char *pre_str, char *in_str)
{
    BTptr bt;
    bt=(BTptr)malloc(sizeof(BTnode));
    bt->data=pre_str[0];
    bt->Lchild=NULL;
    bt->Rchild=NULL;
    if(strlen(pre_str)==1)
        return bt;
    else
    {
        char pre_left[maxsize];
        char in_left[maxsize];
        char pre_right[maxsize];
        char in_right[maxsize];
        int i=0, j=0;
        while(in_str[i]!=bt->data)
        {
            pre_left[i]=pre_str[i+1];
            in_left[i]=in_str[i];
            i++;
        }
        pre_left[i]='\0';
        in_left[i]='\0';
        while(i<=strlen(in_str))
        {
            pre_right[j]=pre_str[i];
            in_right[j]=in_str[i+1];
            i++;j++;
        }
        pre_right[j]='\0';
        in_right[j]='\0';
        if(strlen(pre_left)!=strlen(in_left) || strlen(pre_right)!=strlen(in_right))
        {
            printf("Error\n");
            return 0;
        }
        bt->Lchild=CreateBT(pre_left, in_left);
        bt->Rchild=CreateBT(pre_right, in_right);
        return bt;
    }
}

BTptr Judge(char *pre_str, char *in_str)
{
    if(pre_str==NULL || in_str==NULL || strlen(pre_str)!=strlen(in_str))
        return 0;
    else
        return CreateBT(pre_str, in_str);
}

void PreExchange(BTptr T)
{
    BTptr p;
    if(T!=NULL)
    {
        p=T->Lchild;
        T->Lchild=T->Rchild;
        T->Rchild=p;
        PreExchange(T->Lchild);
        PreExchange(T->Rchild);
    }
}

void PostOrderBT(BTptr T)
{
    if(T!=NULL)
    {
        PostOrderBT(T->Lchild);
        PostOrderBT(T->Rchild);
        printf("%c",T->data);
    }
}

void main()
{
    char pre_str[maxsize];
    char in_str[maxsize];
    gets(pre_str);
    gets(in_str);
    BTptr bt;
    bt=Judge(pre_str, in_str);
    PostOrderBT(bt);
    printf("\n");
    PreExchange(bt);
    PostOrderBT(bt);
}
查看全部
ARookie1234
ARookie1234
2020/04/16 19:13
  • c语言
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复