同样,本题是给出二叉树的前序遍历和中序遍历求后序遍历,本题由于直接给的就是字符串,所以比给节点值的会好很多,因为不需要哈希表了,string自带了find函数。求后序和求前序本质就是一样的,区别在于输出/更新是在递归之前还是递归之后。
#include<bits/stdc++.h>
using namespace std;
void pos(string pre,string in)
{
if(pre.size())
{
char root=pre[0];
int k=in.find(root);
pos(pre.substr(1,k),in.substr(0,k));
pos(pre.substr(k+1),in.substr(k+1));
cout<<root;
}
}
int main()
{
string pre,in;
while(cin>>pre>>in)
{
pos(pre,in);
puts("");
}
return 0;
}