题意:给出一个二叉树的前序和中序,求出这个二叉树的后序
前序可以很清晰的知道根结点。然后再在中序中的左右两边分别就是左子树和右子树。
运用递归可以很容易的完成。
分析:其实不难,充分用好递归思想,发现递归真是美好。
重点就在于几个STL函数的使用。
find函数和substr函数
find函数:返回的是查找的数据的位置,计数也是从0开始
substr函数:求的是起点为pos,长度为n的函数substr(pos,n); 注意:pos是从0开始计数的
贴下代码:(216K,0MS)
C++语言:
#include<iostream>
#include<string>
usingnamespacestd;
typedefstructBiTnode
{
chardata;
BiTnode
*lchild,*rchild;
}*Bitree;
classtree
{
public:
Bitree
creat(string
pre,stringin) //还原二叉树
{
Bitreeroot;
root=NULL;
if(pre.length()>0)
{
root=
newBiTnode;
root->data=
pre[0];
intpostion=
in.find(root->data);
root->lchild=
creat(pre.substr(1,postion),in.substr(0,postion));
root->rchild=
creat(pre.substr(postion+
1),
in.substr(postion+
1));
}
returnroot;
}
voidpos_order_traver(Bitreetree)
{
if(tree==
NULL)return;
else
{
pos_order_traver(tree->lchild);
pos_order_traver(tree->rchild);
cout<<tree->data;
}
}
};
intmain()
{
tree
t;
string
pre,in; //分别为前序和中序
while(cin>>pre>>in)
{
t.pos_order_traver(t.creat(pre,in));
cout<<endl;
}
}
#include<string>
usingnamespacestd;
typedefstructBiTnode
{
}*Bitree;
classtree
{
public:
};
intmain()
{
}