输入一棵二叉树的先序和中序遍历序列,输出其后序遍历序列。
前序遍历:根节点+左子树前序遍历+右子树前序遍历。
中序遍历:左子树中序遍历+根节点+右子树中序遍历。
只需先在前序遍历中找出根节点,再在中序遍历中找出左右子树的节点列表,再递归以上步骤输出即可。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
using namespace std;
string preorder,inorder;
void postorder(int lp, int rp, int li, int ri){
if(lp==rp){
cout<<preorder[lp];return;
}
if(lp>rp || li>ri)return;
int k=inorder.find(preorder[lp]);
postorder(lp+1,lp+k-li,li,k-1);
postorder(lp-li+k+1,rp,k+1,ri);
cout<<preorder[lp];
}
int main(){
cin>>preorder>>inorder;
int len=preorder.size();
postorder(0,len-1,0,len-1) ;
return 0;
}