POJ 2255(二叉树问题)
2013-02-04 20:09
246 查看
题意:根据前序遍历和中序遍历求后序遍历
结题报告:说真的,我对二叉树还是不太能理解,遇到这种题我就不会做,不过看了其他人写的代码,我慢慢的理解了大部分
(转载)递归求解,先根据先序找到根节点,再在中序中找到根节点,根据根节点再中序中的位置分别把先序和中序分成两个子树。(例如:DBACEGF ABCDEFG 第一次找到根节点为D,D在中序中第4个位置,分别把先序分成BAC和EGF,再把中序分成ABC和EFG)利用递归对其求解,得到整个树,再对其进行后序遍历即得到结果。
粘贴一下别人的代码:
另外在本题中用到了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的副本。
结题报告:说真的,我对二叉树还是不太能理解,遇到这种题我就不会做,不过看了其他人写的代码,我慢慢的理解了大部分
(转载)递归求解,先根据先序找到根节点,再在中序中找到根节点,根据根节点再中序中的位置分别把先序和中序分成两个子树。(例如: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的副本。
相关文章推荐
- POJ 2255 二叉树由前序遍历中序遍历得到后序遍历
- poj 2255二叉树
- poj 2255 Tree Recovery(二叉树)
- POJ 2255/hrbust 2022 Tree Recovery【dfs、二叉树的层次遍历】
- POJ 2255 Tree Recovery 二叉树的遍历
- POJ 2255 Tree Recovery ( 二叉树)
- poj 2255 Tree Recovery(二叉树的遍历)
- 【POJ 2255 Tree Recovery】+ 二叉树
- 通过遍历求解二叉树结构poj2255
- poj2255 二叉树给出先序中序求后序序列
- POJ 2255 经典的重建二叉树
- poj 2255 Tree Recovery(做为二叉树的练笔挺不错的)
- POJ 2255 Tree Recovery(二叉树重建)
- 【二叉树】POJ 2255
- POJ 2255 Tree Recovery 二叉树的遍历
- poj 2255:重建二叉树
- poj2255 根据任意二叉树的先序遍历和中序遍历求解后序遍历
- 二叉树的探索 poj 2255
- POJ 2255 Tree Recovery 二叉树基础
- POJ 2255 Tree Recovery【二叉树重建】