1020. Tree Traversals (25)
2016-03-02 20:57
471 查看
1020. Tree Traversals (25)
#include <iostream> #include <stdio.h> #include <vector> #include <cmath> #include <stack> #include <queue> #include <deque> #include <algorithm> #include <map> using namespace std; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; TreeNode *create(vector<int> pre,vector<int> in,int first,int last,int &curRoot){ if (first>last){ curRoot++; return NULL; } TreeNode *p = new TreeNode(pre[curRoot]); auto it = find(in.begin()+first,in.begin()+last+1,pre[curRoot]); int pos = (int)(it- in.begin()); p->right =create(pre, in, pos+1, last, --curRoot); p->left = create(pre, in, first,pos-1, --curRoot); return p; } int main(){ int n; scanf("%d",&n); vector<int>post(n),in(n); for (int i=0; i<n;++i) scanf("%d",&post[i]); for (int i=0; i<n;++i) scanf("%d",&in[i]); int cur = n-1; TreeNode * p = create(post, in, 0, (int)in.size()-1, cur); vector<int>ans; queue<TreeNode *>q; if(p) q.push(p); while (!q.empty()) { p = q.front(); q.pop(); ans.push_back(p->val); if(p->left) q.push(p->left); if(p->right) q.push(p->right); } for (int i=0; i<n; ++i) printf(i==n-1?"%d\n":"%d ",ans[i]); return 0; }
相关文章推荐
- HDOJ-2056(Rectangles)
- 区间K大数查询
- poj3292 Semi-prime H-numbers 2012-09-05
- 优先级
- angular.js 中同步视图和模型数据双向绑定,$watch $digest $apply 机制
- ArrayList 、Vector 的区别
- setTimeout中this指向全局windows
- 执行环境及作用域
- File
- 操作系统笔记(一)
- lua.c:80:31: fatal error: readline/readline.h: No such file or directory
- 数论总结 2012-09-05
- poj 2891 Strange Way to Express Integers 2012-09-05
- LA 4728 对踵点对
- C语言常见单链表面试题(2)
- 混合云
- 微信公众平台开发学习记录(2)————自定义菜单创建
- sql-mode
- AppCompat v23.2 — DayNight
- POJ Optimal Milking 2012-08-28