ACBFGED ABCDEFG CDAB CBAD
DBACEGF BCAD
思路:看到本题首先想到的是重建一个二叉树,由中序遍历和后序遍历可以重新构建一颗二叉树,然后先序遍历输出求的结果
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node{
char num;
struct node *lchild,*rchild;
}NODE,*PNODE;
void buildTree(PNODE * root,char*post,char*in,int len)/*root表示根节点,post表示后序遍历的结果,in表示中序遍历的结果,len表示当前子树的长度*/
{
if(len==0)
{
*root=NULL;
return;
}
PNODE node=(PNODE)malloc(sizeof(NODE));
node->num=post[len-1];
node->lchild=node->rchild=NULL;
*root=node;
char *s=strchr(in,node->num);//找到根节点在中序遍历中的位置
int leftlen=strlen(in)-strlen(s);//左子树的长度
int rightlen=len-leftlen-1;//右子树的长度
buildTree(&(*root)->lchild,post,in,leftlen);//递归建左子树
buildTree(&(*root)->rchild,post+leftlen,s+1,rightlen);//递归建立右子树
}
void bianliTree(PNODE root)//先序遍历
{
if(root==NULL)
return ;
printf("%c",root->num);
bianliTree(root->lchild);
bianliTree(root->rchild);
}
int main()
{
char post[26],in[26];
while(scanf("%s %s",post,in)!=EOF)
{
PNODE root=NULL;
buildTree(&root,post,in,strlen(in));
bianliTree(root);
printf("\n");
}
return 0;
}
大神代码:
#include<stdio.h>
#include<string.h>
void ReBuild(char *pre, char *in,char *post, int len)
{
if(len>0)
{
int n =strchr(in,post[len-1])-in;
ReBuild(pre+1,in,post,n);
ReBuild(pre+n+1,in+n+1,post+n,len-n-1);
pre[0]=post[len-1];
}
}
int main()
{
char pre[30],in[30],post[30];
int len;
while(~scanf("%s%s",post,in))
{
len=strlen(post);
ReBuild(pre,in,post,len);
pre[len]=0;
puts(pre);
}
}原文:http://blog.csdn.net/u013238646/article/details/43154465