您的位置:首页 > 其它

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;

   }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: