重建二叉树
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
3
- 描述
- 题目很简单,给你一棵二叉树的后序和中序序列,求出它的前序序列(So easy!)。
- 输入
-
输入有多组数据(少于100组),以文件结尾结束。
每组数据仅一行,包括两个字符串,中间用空格隔开,分别表示二叉树的后序和中序序列(字符串长度小于26,输入数据保证合法)。 - 输出
- 每组输出数据单独占一行,输出对应得先序序列。
- 样例输入
-
ACBFGED ABCDEFG CDAB CBAD
- 样例输出
-
DBACEGF BCAD
来源
第一种做法:
#include<stdio.h> #include<iostream> #include<algorithm> #include<stdio.h> using namespace std; struct Node{//二叉树结构体 char data; Node * lchild; Node * rchild; }; Node *build(string hou,string in) { Node *root=NULL; if(hou.length()>0) { int k=hou.length(); root=new Node; root->data=hou[k-1];//后序遍历的最后访问根节点。 int index=in.find(hou[k-1]);//在中序序列中找到当前树的根结点 root->lchild=build(hou.substr(0,index),in.substr(0,index));//递归左子树 root->rchild=build(hou.substr(index,k-1-index),in.substr(index+1));//递归右子树 //substr复制子字符串,要求从指定位置开始,并具有指定的长度。 } return root; } void print(Node *root)//输出先序序列 { if(root!=NULL) { printf("%c",root->data);//先输出根结点 post(root->lchild);//再访问左子树 post(root->rchild);//最后访问右子树 } } int main() { string hou,in; while(cin>>hou>>in)//读入后序和中序序列 { Node* root=build(hou,in);//将后序和中序序列转换为先序序列 print(root);//先序序列递归输出 cout<<endl; } 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;//strchr函数在一个串中查找给定字符的第一个匹配之处
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);
}
return 0;
}