JOJ 1329: Tree(重建二叉树)
来源:互联网 发布:淘宝交纳保证金 编辑:程序博客网 时间:2024/04/30 20:38
给出二叉树的中序和后序遍历,求树的根到叶的最小结点和的路径上的叶节点的值;思路是在后序找出根,在中序遍历中找出其位置,确定左右儿子,递归建树,在建树的过程直接构建所求。
#include <cstdio>#include <string.h>const int maxn=255;const int Inf=0x7fffffff;char instr[maxn];char pstr[maxn];int num[10],cnt,head[maxn];int node1 [50];int node2 [50];struct edge{ int v,adj,next;}e[maxn];int min,ans;void build (int n , int* n1 , int * n2,int sum){ if(n==0)return ; sum+=*(n2+n-1); if(n==1) { if(min>sum) {min=sum ; ans=(*n1);} return ; } int pos=-1; for (int i=0 ; i<n ; ++i)if(n1[i]==n2[n-1]){pos=i;break;} //printf("pos=%d\n",pos); build(pos,n1,n2,sum); build(n-pos-1,n1+pos+1,n2+pos,sum); //printf("%d \n",node2[n-1]);}int main (){ int n,t,i; scanf("%d",&t); getchar(); while (t--) { min=Inf; cnt=0; memset (head,-1,sizeof(head)); gets(instr); gets(pstr); int len =strlen(instr); int len2 =strlen(pstr); int t,cnt=0,p; for (i=0 ,p=0; i<len ; i++) { if(instr[i+1]==' ' ||instr[i+1]=='\0') { num[p++]=instr[i]-'0'; if(p==1)node1[cnt]=num[0]; if(p==2)node1[cnt]=num[0]*10+num[1]; if(p==3)node1[cnt]=num[0]*100+num[1]*10+num[2]; cnt++; p=0; } else if(instr[i]!=' ')num[p++]=instr[i]-'0'; //printf("%d\n",num[p]); } cnt=0; for (i=0 ,p=0; i<len ; i++) { if(pstr[i+1]==' ' || pstr[i+1]=='\0') { num[p++]=pstr[i]-'0'; if(p==1)node2[cnt]=num[0]; if(p==2)node2[cnt]=num[0]*10+num[1]; if(p==3)node2[cnt]=num[0]*100+num[1]*10+num[2]; cnt++; p=0; } else if(pstr[i]!=' ')num[p++]=pstr[i]-'0'; } for (i= 0 ; i< cnt ;++i ) build(cnt,node1,node2,0); printf("%d\n",ans); } return 0;}
- JOJ 1329: Tree(重建二叉树)
- joj 1329 二叉树
- UVA 536 Tree Recovery 二叉树重建(重建二叉树+DFS)
- HDU 1710-Binary Tree Traversals(重建二叉树)
- 1020. Tree Traversals (25) (重建二叉树)
- UVA 536 - Tree Recovery(二叉树重建)
- HDU1710 Binary Tree Traversals(二叉树重建模板609)
- (二叉树重建)Tree Recovery(P2255)
- POJ2255,Tree Recovery,二叉树重建
- uva712 S-Tree (假二叉树重建)
- POJ 2255 Tree Recovery(二叉树重建)
- 二叉树重建(Tree Recovery ,UVa536)
- UVa 536 Tree Recobery 二叉树重建
- uva 536 Tree Recovery(二叉树重建)
- 重建二叉树 Binary Tree Traversals HDU
- JOJ 2445: Tree 线段树
- 重建二叉树(树)
- poj2255(二叉树重建)
- 写程序就是我的图腾,如果发现直接无错误运行,说明我在梦里。
- C++经典
- Matlab 图像处理实验
- mssql日志清理方法
- ASCII码表
- JOJ 1329: Tree(重建二叉树)
- JS冒泡事件解决方案
- 随想:增强类的重用性
- gauce学习笔记:grid
- Rockie's Android Porting Guide(4)——Add SD card to your system
- webtrends 分析报告
- 版本控制 不能checkout “configureration rule”
- 前所未有的Windows7多媒体中心
- IE 9 安装参数