指针建树uva548
2014-03-01 20:21
375 查看
题意:给出中序遍历和后序遍历,找出最短路径上的叶结点的值
思路:先建树然后dfs找
思路:先建树然后dfs找
#include<iostream> #include<cstdio> #include<string> #include<sstream> #include<cstring> #include<vector> using namespace std; struct node { int data; node *left,*right; node() { data=0; left=right=NULL; } }; const int INF=1000000000; const int maxn=10010; int inorder[maxn],postorder[maxn],n,max1; vector<int> result; vector<node *>pos; node * build_tree(int len,int *in,int *po) { if(len<=0)return NULL; int i=len-1; while(po[len-1]!=in[i])i--; node *f=new node(); f->data=po[len-1]; f->left=build_tree(i,in,po); f->right=build_tree(len-1-i,in+i+1,po+i); return f; } void dfs(node *p,int sum) { if(!p->left&&!p->right) { result.push_back(sum+p->data); pos.push_back(p); return; } if(p->left)dfs(p->left,sum+p->data); if(p->right)dfs(p->right,sum+p->data); } int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); #endif string s; while(scanf("%d",&inorder[0])!=EOF) { n=1; while(getchar()!='\n') cin>>inorder[n++]; for(int i=0;i<n;i++) cin>>postorder[i]; node *root=build_tree(n,inorder,postorder); result.clear(); pos.clear(); dfs(root,0); //cout<<n<<endl; int max1=INF,ans; for(int i=0;i<result.size();i++) if(result[i]<max1){ans=i;max1=result[i];} cout<<pos[ans]->data<<endl; } return 0; }
相关文章推荐
- jQuery常用方法(五)-jQuery CSS
- Hibernate的关联映射---6.1.7: 双向1-1关联
- 【转】边缘连接
- Hibernate的关联映射---6.1.6: 双向n-n关联
- 男人必须具有的东西
- 黑马程序员_Java String类
- 100天坚持行动总结---2
- CMD命令之ping的学习
- Linux基本命令学习(一)
- Hibernate的关联映射---6.1.5: 双向1-n关联
- python ConfigParser 模块学习
- win7下部署eclipse访问Linux下hadoop
- HDU 3518 Boring counting
- iframe document对象
- Hibernate的关联映射---6.1.4: 单向n-n关联
- HDU 4509 湫湫系列故事——减肥记II
- 解决Servlet的乱码问题
- 用友NC57定时任务编写
- TCP/IP,http,socket,长连接,短连接——小结。
- SpringMVC 文件上传配置,多文件上传,使用的MultipartFile