题目描述
给定二叉树的前序遍历和中序遍历,输出二叉树的后序遍历序列。
思路
①前序遍历的第一个结点是树根,寻找树根在中序遍历中的位置,可以将树分为两半。
②分为两半后,仍然可以得到前一半和后一半的前需、中序遍历序列,使用递归重复上述步骤即可解题。
代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
using namespace std;
string s1,s2;
string dfs(string p,string m)
{
if(m.size()){
int k = m.find(p[0]);
dfs(p.substr(1,k),m.substr(0,k)); #前序:从1开始后面k个字符;中序:从0开始后k个
dfs(p.substr(k+1),m.substr(k+1)); #前序、中序:从k+1位置开始后面所有字符;
cout<<p[0]; #最后输出满足后序遍历的条件
}
}
int main()
{
while(cin>>s1>>s2){
dfs(s1,s2);
cout<<endl;
}
return 0;
}