这个题看着比较简单就先做了,虽然用了不少时间,但是也学到了不少东西,对二叉树的遍历有了进一步的了解,然后就是提交答案的时候,有一些细节没有注意,提交了3次才过
思路:递归建立二叉树,用映射给节点编号,直到中序遍历建立二叉树结束为止,建立的同时输出后序遍历
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
using namespace std;
char x[1024],z[1024],ltr[1024],rtr[1024];
map<char,int> tree;
void tmap(char s[])
{
for(int i=0;i<strlen(s);i++)
{
tree[s[i]] = i;
}
}
char build(int D1,int D2,int L1,int L2)
{
if(L1>L2) return '0';
char root=x[D1];
int p = L1;
while(z[p]!=x[D1]) p++;
int cnt = p-L1;
int troot = tree[root];
ltr[troot] = build(D1+1,D1+cnt,L1,p-1);
rtr[troot] = build(D1+cnt+1,D2,p+1,L2);
cout<<root;
return root;
}
int main()
{
while(cin>>x>>z)
{
tree.clear();
memset(ltr,'0',sizeof(ltr));
memset(rtr,'0',sizeof(rtr));
tmap(x);
int n = strlen(x);
tree['0'] = -1;
build(0,n-1,0,n-1);
cout<<endl;
}
return 0;
}