很不错的一道题目,题意是给定二叉树的前序遍历和中序遍历,输出二叉树的后续遍历,总的思想是递归,找到前序遍历中的根节点在中序遍历中的位置,从这个位置将中序遍历分为左子树和右子树,然后递归建树即可。
需要明白二叉树前序,中序,后序遍历之间的关系,有助于帮助像我一样刚开始学习二叉树的朋友更深入的理解二叉树。
题目链接:http://poj.org/problem?id=2255
第一种方法的代码,根据前序和中序直接建树,然后后续遍历输出即可,思路简单,但程序比较复杂,参考了网上大牛的程序,用了指针的指针来传参,写了很久终于结果正确了,但是提交后编译错误,现在也没有找到错误在哪,指针果然还是不好理解,要加强对指针的理解了。如果有哪位大神知道小弟哪里错了,请指出来,感激不尽。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
char date;
node *lchild,*rchild;
};
int t,f;
void build(char *a,char *b,node **p)
{
int i,k;
(*p)=(struct node*)malloc(sizeof(node));
(*p)->lchild=NULL;
(*p)->rchild=NULL;
k=strlen(b);
(*p)->date=*a;
if(k==1)
return ;
for(i=0;i<k;i++)
{
if(*(b+i)==*a)
break;
}
if(i==0)
{
build(a+1,b+1,&(*p)->rchild);
}
else if(i==k-1)
{
*(b+i)='\0';
build(a+1,b,&(*p)->lchild);
}
else
{
*(b+i)='\0';
build(a+1,b,&(*p)->lchild);
build(a+i+1,b+i+1,&(*p)->rchild);
}
}
void last(node *s)
{
if(s!=NULL)
{
last(s->lchild);
last(s->rchild);
printf("%c",s->date);
}
}
int main()
{
char a[100],b[100];
node *root;
while(scanf("%s%s",a,b)!=-1)
{
f=0;
root=NULL;
build(a,b,&root);
last(root);
printf("\n");
}
return 0;
}
这个是AC的代码,程序比上一个简单多了,但是需要很好的理解三种遍历的关系.
#include<stdio.h>
#include<string.h>
char s[100];
void build(int n,char *a,char *b,char *s)
{
int i,j,k,m;
if(n<=0)
return ;
k=strlen(b);
for(i=0;i<k;i++) //找到根节点在中序中位置
{
if(*(b+i)==*a)
break;
}
*(b+i)='\0';
build(i,a+1,b,s); //分为左右子树,递归
build(n-i-1,a+i+1,b+i+1,s+i);
s[n-1]=*a; //核心思想,根节点的位置是后续遍历的最后
}
int main()
{
int n;
char a[100],b[100];
memset(s,0,sizeof(s));
while(scanf("%s%s",a,b)!=-1)
{
n=strlen(a);
build(n,a,b,s);
s[n]='\0';
printf("%s\n",s);
}
return 0;
}