例如给定前序和中序:
前序:abdfghiec
中序:fdhgibeac
前序的第一个元素就是树的根节点,则:
a bdfghiec
fdhgibe a c
根据划分,c就是a的左子树,继续划分刚写出的前中序列
b dfhiec
fdhgi b e
以此类推,可写出代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node* position;
typedef position bintree;
struct node
{
int data;
bintree left;
bintree right;
};
bintree build(char *pre,char *in,int size)
{
if(size<=0)
return NULL;
//先在中序遍历中找到根节点
int i;
for(i=0;i<size;i++)
if(*(in+i)==*pre)
break;
//确定根节点
bintree tree;
tree=(bintree) malloc(sizeof(struct node));
tree->data=*pre;
tree->left=build(pre+1,in,i);
tree->right=build(pre+i+1,in+i+1,size-1-i);
return tree;
}
void postordertraversal(bintree t)
{
if(t)
{
postordertraversal(t->left);
postordertraversal(t->right);
printf("%c ",t->data);
}
}
int main()
{
char pre[50],in[50];
scanf("%s %s",pre,in);
int size=strlen(in);
bintree abc=build(pre,in,size);
postordertraversal(abc);
return 0;
}