POJ 2255(二叉树问题)
来源:互联网 发布:电火花线切割如何编程 编辑:程序博客网 时间:2024/06/04 20:08
题意:根据前序遍历和中序遍历求后序遍历
结题报告:说真的,我对二叉树还是不太能理解,遇到这种题我就不会做,不过看了其他人写的代码,我慢慢的理解了大部分
(转载)递归求解,先根据先序找到根节点,再在中序中找到根节点,根据根节点再中序中的位置分别把先序和中序分成两个子树。(例如: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二叉树
- POJ 2255 Tree Recovery ( 二叉树)
- POJ 2255 Tree Recovery(二叉树)
- poj 2255:重建二叉树
- poj 2255 二叉树遍历
- POJ - 2255 二叉树遍历
- poj 2255 Tree Recovery(求后序遍历,二叉树)
- poj 2255 Tree Recovery(二叉树的遍历)
- POJ 题目2255Tree Recovery(二叉树)
- POJ 2255 Tree Recovery(二叉树遍历)
- 二叉树的序号(poj 二叉树)
- POJ 2255 Tree Recovery 二叉树遍历
- POJ 2255 Tree Recovery [二叉树]
- Poj 2255-Tree Recovery//二叉树,递归
- 二叉树的探索 poj 2255
- POJ 2255 重构二叉树
- 关于Debug和Release之本质区别 .
- 内存泄漏测试小工具
- 《ASP.NET MVC 入门系列教程》索引贴(转)
- 10条找工作箴言!让你年末跳槽不再盲目!
- DLL动态链接库和LIB静态链接库之程序员经验分析
- POJ 2255(二叉树问题)
- c++中RTTI的观念和使用
- 书
- CRC原理及其逆向破解方法
- 进程创建时 ObOpenObjectByPointer 导致蓝屏
- 显式加载DLL并使用 DLL 中的类
- 使用函数优化字符串转数字/日期……,非数字将返回空
- 线程同步技术(一)
- solr + eclipse 调试环境搭建