这题要是做数据结构的练习题挺好的。就是给出前序和中序序列,要求后序序列。在先序序列中,第一个元素为二叉树的根,之后为它的左子树和右子树的先序序列;在中序序列中,先是左子树的中序序列,然后是根,再就是右子树的中序序列。由此就可以递归的建立起这棵二叉树了。
递归有时真的很美。。。
Node* create(const string& pres,const string& ins)
{
Node* root;
if(pres.length()>0)
{
root=new Node;
root->data=pres[0];
int index=ins.find(root->data);
root->left=create(pres.substr(1,index),ins.substr(0,index));
root->right=create(pres.substr(index+1),ins.substr(index+1));
}
else root=NULL;
return root;
}
具体代码如下:
#include<iostream>
#include<string>
using namespace std;
struct node
{
char data;
node *lchirld;
node *rchirld;
};
node *create(string pre,string in)
{
node *root;
root=NULL;
if(pre.length()>0)
{
root=new node;
root->data=pre[0];
int index=in.find(root->data);
root->lchirld=create(pre.substr(1,index),in.substr(0,index));
root->rchirld=create(pre.substr(index+1),in.substr(index+1));
}
return root;
}
void postorder(node *&root)
{
if(root!=NULL)
{
postorder(root->lchirld);
postorder(root->rchirld);
cout<<root->data;
}
}
int main()
{
string pre,in;
while(cin>>pre>>in)
{
node *root;
root=create(pre,in);
postorder(root);
cout<<endl;
}
return 0;
}
另外在本题中用到了string文件库的两个函数find()与substr();
具体解释如下:
是s.find(args)在S中查找args第一次出现的位置下标。而substr()有以下几种操作
1、s.substr(pos,n) 返回一个string类型的字符串,它包含s中从下标pos开始的n个字符。
2、s.substr(pos) 返回一个string类型的字符串,它包含从下标pos开始到s末尾的所有字符。
3.s.substr()返回s的副本。