二叉树之已知前序和中序遍历求后序遍历(POJ &&HDU )
2015-09-16 14:51
399 查看
POJ2255【题目链接】click here~~
代码:
写法仿照上题。
代码:
/* * Problem: POJ No.2255 && UVA 536 * Running time: 0MS * Complier: G++ * Author: javaherongwei * Create Time: 2015-08-18 10:35:06 星期五 * binary search tree */ #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> using namespace std; typedef long long LL; const int N= 1e2+10; char res ,pre ,in ,last ; void findlast(int n,char* pre,char* in,char* res)///递归构造,输入先序遍历,中序遍历,求后序遍历 { if(n<=0) return ; int p=strchr(in,pre[0])-in;///找到根节点在中序遍历的位置 findlast(p,pre+1,in,res);///递归构造左子树的后序遍历 findlast(n-p-1,pre+p+1,in+p+1,res+p);///递归构造右子树的后序遍历 res[n-1]=pre[0];///添加根节点到最后面 } int main() { while(scanf("%s%s",pre,in)==2) { int n=strlen(in); findlast(n,pre,in,res); res ='\0'; printf("%s\n",res); } return 0; } 另一种写法: #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> using namespace std; typedef long long LL; const int N=100+10; char pre ,in ,last ; void Find_Last(int p1,int p2,int q1,int q2,int root) { if(p1>p2) return; for(root=q1; in[root]!=pre[p1]; ++root); Find_Last(p1+1,p1+root-q1,q1,root-1,0); Find_Last(p1+root+1-q1,p2,root+1,q2,0); printf("%c",in[root]); } int main() { while(scanf("%s%s",pre,in)==2) { int len=strlen(pre)-1; Find_Last(0,len,0,len,0); puts(""); } return 0; } /* *输入先序遍历,中序遍历,求后序遍历 *样例: DBACEGF ABCDEFG ACBFGED BCAD CBAD CDAB */HDU 1710【题目链接】:click here~~
写法仿照上题。
/* * Problem: HDU No.1710 * Running time: 62MS * Complier: G++ * Author: javaherongwei * Create Time: 2015-09-16 14:37:06 星期三 * binary search tree */ #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> using namespace std; typedef long long LL; const int N=1e4+10; int pre ,in ,last ; void Find_Last(int p1,int p2,int q1,int q2,int root,int ck) // 标记一个变量 { if(p1>p2) return; for(root=q1; in[root]!=pre[p1]; ++root); Find_Last(p1+1,p1+root-q1,q1,root-1,0,0); Find_Last(p1+root+1-q1,p2,root+1,q2,0,0); if(ck==1) printf("%d",in[root]); else printf("%d ",in[root]); } int main(){ int t;while(~scanf("%d",&t)){ for(int i=0; i<t; ++i) scanf("%d",&pre[i]); for(int i=0; i<t; ++i) scanf("%d",&in[i]); Find_Last(0,t-1,0,t-1,0,1); puts(""); } return 0; }
相关文章推荐
- C++中获取数据类型typeid
- 编码的技巧
- 可重入函数
- Binary Tree Level Order Traversal II
- IOS 的恢复方法总结
- OpenLayers Labeled Features Example
- js创建Form表单并提交
- 各种数组排序方法
- Vyatta2.0发布 博科押宝SDN
- C内存对齐
- poj 1984 并查集(在线查询曼哈顿距离)
- hdu 2222 Keywords Search(AC自动机)
- 淘宝如何跨域获取Cookie分析
- (整理篇三)Android知识图谱
- [Elasticsearch] 多字段搜索 (六) - 自定义_all字段,跨域查询及精确值字段
- iOS申请真机调试证书 图文详解
- Cisco.PIX防火墙配置
- 用JS scrollHeight方法实现textarea输入高度自适应的方法
- 调试笔记
- 关于FD_CLOEXEC的一个故事 http://leave001.blog.163.com/blog/static/162691293201251810343121/