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