已知后序与中序,求前序

来源:互联网 发布:复杂网络包括 编辑:程序博客网 时间:2024/06/05 07:04
//in+post->pre;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node{
char data;
struct node *left;
struct node *right;
}Node;
void preTravel(Node *root)
{
printf("%c",root->data);//visit(root value);
if(root->left!=NULL)
preTravel(root->left);
if(root->right!=NULL)
preTravel(root->right);
}
void buildTree(char in[],char post[],Node *root){
int len=strlen(in);
if(len==0)
return;
char *p=strchr(in,post[len-1]);
int pos=(int)(p-in);
root->data=post[len-1];
if(pos!=0){
Node *left=(Node *)malloc(sizeof(struct node));
root->left=left;
left->data=post[pos-1];
char* left_in=(char*)malloc(pos*sizeof(char));
        char* left_post=(char*)malloc(pos*sizeof(char));
        strncpy(left_in,in,pos);
        strncpy(left_post,post,pos);
        buildTree(left_in,left_post,left);



}
if(pos!=len-1){
Node *right=(Node*)malloc(sizeof(struct node));
root->right=right;
right->data=post[len-2];
char* right_in=(char*)malloc((len-1-pos)*sizeof(char));
        char* right_post=(char*)malloc((len-1-pos)*sizeof(char));
        strncpy(right_in,in+pos+1,len-1-pos);
        strncpy(right_post,post+pos,len-1-pos);
        buildTree(right_in,right_post,right);


}




}
int main(){
int i;
char ch;
char in[100],post[100];
    for(i=0;(ch=getchar())!=' ';i++)
    in[i]=ch;
    in[i]='\0';
    for(i=0;(ch=getchar())!='\n';i++)
    post[i]=ch;
  in[i]='\0';
    Node*root=(Node *)malloc(sizeof(struct node));
    buildTree(in,post,root);
    preTravel(root);
    printf("\n");
    return 0;
}
0 0