您的位置:首页 > 其它

POJ 2255(二叉树问题)

2013-02-04 20:09 246 查看
题意:根据前序遍历和中序遍历求后序遍历

结题报告:说真的,我对二叉树还是不太能理解,遇到这种题我就不会做,不过看了其他人写的代码,我慢慢的理解了大部分

(转载)递归求解,先根据先序找到根节点,再在中序中找到根节点,根据根节点再中序中的位置分别把先序和中序分成两个子树。(例如:DBACEGF ABCDEFG 第一次找到根节点为D,D在中序中第4个位置,分别把先序分成BAC和EGF,再把中序分成ABC和EFG)利用递归对其求解,得到整个树,再对其进行后序遍历即得到结果。

粘贴一下别人的代码:

#include <iostream>
#include <stdio.h>
#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)//原本用(node *&root),可是我不明白为什么,我去掉“&”时也AC了
{
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的副本。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: