原理解说(摘自百度)
如前序 为 ABDECGF
中序 为 BDACGEF
先 根据前序第一个节点 把中序分为BD和CGEF两部分,A为根节点,A左边为左子树,右边为右子树。再把左右子树分别做上述步骤。
以此类推 根据第二,第三...个节点构成二叉树 A
B E
D C F
G B
再根据后序的性质得到DBGCBFEA
知道后序中序 求前序类似。
知道后序前序,无法求得中序。
下面两种都可以
node* getroot(int pre[],int mid[],int n){
if(n == 0) return 0;
node *p = new node;
p->value = pre[0];
int i;
for(i=0;i<n;i++)
{
if(mid[i] == pre[0]) break;
}
p->left = getroot(pre+1,mid,i);
p->right = getroot(pre+i+1 ,mid+i+1,n-i-1);
return p;
}
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
struct node{
char ch;
node* left;
node* right;
node(){
left=NULL;
right=NULL;
}
};
void getroot(string s1,string s2,node* &n){
int len1=s1.length();
int len2=s2.length();
n->left=new node();
n->right=new node();
if(len1==0||len2==0){
n=NULL;
return ;
}
string new_s11,new_s12,new_s2,new_s3;
n->ch=s1[0];
int j=0;
for(j=0; j < len2; ++j){
if(s2[j]==s1[0]) break;
new_s2+=s2[j];
}
j++;
for(; j < len2; ++j)
new_s3+=s2[j];
for(j=1; j < len1; ++j){
if(new_s3.find(s1[j])!=string::npos) break;
new_s11+=s1[j];
}
for(; j < len1; ++j)
new_s12+=s1[j];
//cout << new_s11+" 1" << endl << new_s12+" 1" << endl << new_s2+" 1" << endl << new_s3+" 1" << endl << endl;
getroot(new_s11,new_s2,n->left);
getroot(new_s12,new_s3,n->right);
}
void pos_tra(node *n){
if(n==NULL) return;
pos_tra(n->left);
pos_tra(n->right);
cout << n->ch;
}
int main()
{
node* n=new node();
string s1="abdgcefh";
string s2="dgbaechf";
getroot(s1,s2,n);
pos_tra(n);
}