题目:codevs 1013;
思路:已知后序遍历和中序遍历,不难知道后序的最后一个即为二叉树的根节点,在中序中找到这个节点,就可以知道左右子树的长度,多次递归即可求解,这题其实可以不用先序遍历二叉树,因为后序反过来就是先序了,所以建树的同时输出即可~
ps:一开始弄错了substr()函数第二个参数的含义,其第二个参数为截取字符串的长度,我错解为结束截取的位置,导致各种bug,不过终于还是改好了;
#include<iostream>
#include<string>
//#include<queue>
using namespace std;
typedef struct node
{
char data;
node *lch;
node *rch;
}*tree,node;
void creat(tree &h,string &mi,string &pos)
{
if(mi.empty())
{
h = NULL;
return;
}
int pos_len = pos.size();
int mi_len = mi.size();
int p = mi.find(pos[pos_len-1]);
string mi_lch = mi.substr(0,p);
string mi_rch = mi.substr(p+1,pos_len-p-1);
string pos_lch = pos.substr(0,p);
string pos_rch = pos.substr(p,pos_len-p-1);
h = new node;
if(h !=NULL)
{
h->data = pos[pos_len-1];
cout << h->data;
creat(h->lch,mi_lch,pos_lch);
creat(h->rch,mi_rch,pos_rch);
}
}
int main()
{
string mid,post;
cin >> mid;
cin >> post;
tree root;
creat(root,mid,post);
return 0;
}