已知中序先序求后序
#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
char inorder[100];
char preorder[100];
void build(int in_l, int in_r, int pre_l, int pre_r){
int mid = strchr(inorder, preorder[pre_l]) - inorder;
//递归求左树: 中序子树下标 先序子树下标
if(mid > in_l) build(in_l, mid-1, pre_l + 1, pre_l + mid - in_l);
//递归求右树: 中序子树下标 先序子树下标
if(mid < in_r) build(mid+1, in_r, pre_r -in_r+mid + 1, pre_r );
cout<<inorder[mid]; //输出
}
int main()
{
cin>>inorder>>preorder;
build(0, strlen(inorder) - 1, 0, strlen(preorder) - 1);
return 0;
}
已知中序后序求先序 (与上面一个道理)
#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
char inorder[1000];
char postorder[1000];
//分治
void build(int l1, int r1, int l2, int r2)
{
int mid = strchr(inorder, postorder[r2]) - inorder;
cout<<inorder[mid];
if(mid > l1) build(l1, mid - 1, l2, l2 + mid - l1 - 1);
// if(mid < r1) build(mid + 1, r1, r2 + mid - r1, r2 - 1);
if(mid < r1) build(mid + 1, r1, l2+mid-l1, r2 - 1);
}
int main()
{
cin>>inorder>>postorder;
int len = strlen(inorder);
build(0, len-1, 0, len-1);
return 0;
}