poj 2255 Tree Recovery(做为二叉树的练笔挺不错的)
2013-06-13 15:40
387 查看
题意:给出一个二叉树的前序和中序,求出这个二叉树的后序
分析:其实不难,充分用好递归思想,发现递归真是美好。
前序可以很清晰的知道根结点。然后再在中序中的左右两边分别就是左子树和右子树。
运用递归可以很容易的完成。
重点就在于几个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<
4000
span style="color:rgb(48,48,48);">>>pre>>in)
{
t.pos_order_traver(t.creat(pre,in));
cout<<endl;
}
}
分析:其实不难,充分用好递归思想,发现递归真是美好。
前序可以很清晰的知道根结点。然后再在中序中的左右两边分别就是左子树和右子树。
运用递归可以很容易的完成。
重点就在于几个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<
4000
span style="color:rgb(48,48,48);">>>pre>>in)
{
t.pos_order_traver(t.creat(pre,in));
cout<<endl;
}
}
相关文章推荐
- POJ 2255 Tree Recovery && Ulm Local 1997 Tree Recovery (二叉树的前中后序遍历)
- POJ 2255 Tree Recovery(二叉树)
- poj 2255 Tree Recovery(求后序遍历,二叉树)
- POJ 2255 Tree Recovery ( 二叉树)
- poj 2255 Tree Recovery(二叉树)
- poj 2255 Tree Recovery(二叉树的遍历)
- POJ 2255 Tree Recovery(二叉树重建)
- poj 2255 Tree Recovery (二叉树的顺序遍历)
- POJ 2255 Tree Recovery
- poj 2255 Tree Recovery
- POJ 2255 Tree Recovery
- POJ 2255 Tree Recovery(还原树)
- poj-2255-Tree Recovery(tree)
- poj 2255 二叉树 已知先序和中序,求后序
- poj 2255 Tree Recovery
- poj 2255——Tree Recovery
- POJ 2255 经典的重建二叉树
- POJ 2255 Tree Recovery
- poj——2255——Tree Recovery
- POJ2255,Tree Recovery,二叉树重建