题意
一棵二叉树由 ABC...XYZ来代表节点表示
现在,给予先序遍历和中序遍历,还原树,输出后序遍历
Sample Input
DBACEGF ABCDEFG
BCAD CBAD
Sample Output
ACBFGED
CDAB
思路 基本树还原,边还原边输出树
WA 1
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <sstream>
#include <string>
#define maxn 30
using namespace std;
struct node{
int r,l;
}tree[maxn];
string s1,s2;
int build(int l1,int r1, int l2, int r2){
if(l1>r1)
return 0;
int root=s1[l1]-'A'+1;
int len=0;
for(int i = l2 ; i<=r2 ; i++){
if(s1[l1]==s2[i])
break;
len++;
}
tree[root].l=build(l1+1,l1+len,l2,l2+len-1);
tree[root].r=build(l1+1+len,r1,l2+len+1,r2);
}
int dfs(int x){
if(tree[x].l)
dfs(tree[x].l);
if(tree[x].r)
dfs(tree[x].r);
printf("%c",x+'A'-1);
}
int main(){
while(cin>>s1>>s2){
int n = s1.size();
build(0,n-1,0,n-1);
int root=s1[0]-'A'+1;
dfs(root);
printf("\n");
}
}
到现在都还是没能够找到错误,dfs后序遍历没问题啊,uDebug上也没出问题
后来 讲建树与输出改在一起了,就ac了
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <sstream>
#include <string>
#define maxn 30
using namespace std;
struct node{
int r,l;
}tree[maxn];
string s1,s2;
int build(int l1,int r1, int l2, int r2){
if(l1>r1)
return 0;
int root=s1[l1]-'A'+1;
int len=0;
for(int i = l2 ; i<=r2 ; i++){
if(s1[l1]==s2[i])
break;
len++;
}
tree[root].l=build(l1+1,l1+len,l2,l2+len-1);
tree[root].r=build(l1+1+len,r1,l2+len+1,r2);
printf("%c",s1[l1]);
}
int main(){
while(cin>>s1>>s2){
int n = s1.size();
build(0,n-1,0,n-1);
printf("\n");
}
}