D
/
/
B E
/ \
/ \
A C G
/
/
F
DBACEGF ABCDEFG BCAD CBAD
ACBFGED CDAB
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node{
char data;
struct node*lchild,*rchild;
}NODE,*PNODE;
PNODE rebuildTree(char *post,char*in,int len)//post表示先序遍历的结果,in表示中序遍历的结果,len表示当前子树的长度
{
if(len<=0)
return NULL;
PNODE node=(PNODE)malloc(sizeof(NODE));
node->data=*post;
char* k=strchr(in,node->data);//找到根节点所在的中序的位置
int leftlen=strlen(in)-strlen(k);//左子树长度
int rightlen=len-leftlen-1;//右子树长度
node->lchild=rebuildTree(post+1,in,leftlen);//递归建立左子树
node->rchild=rebuildTree(post+leftlen+1,in+leftlen+1,rightlen);//递归建立右子树
return node;
}
void print(PNODE root)//后序遍历输出结果
{
if(root==NULL)
return;
print(root->lchild);
print(root->rchild);
printf("%c",root->data);
}
int main()
{
char post[27],in[27];
while(~scanf("%s%s",post,in))
{
PNODE root=NULL;
root=rebuildTree(post,in,strlen(in));
print(root);
printf("\n");
}
return 0;
}原文地址:http://blog.csdn.net/u013238646/article/details/43483489