ACM篇:Uva 548 -- Tree
2017-01-11 10:46
399 查看
#include <iostream> #include <cstdio> #include <vector> #include <algorithm> #include <cstring> #include <sstream> #include <cmath> using namespace std; const int SUP = 999999999; struct Node { int val; Node *left; Node *right; Node(int v): val(v), left(NULL), right(NULL) {} }; vector<int> in_order; vector<int> post_order; int read_list(vector<int> &a) { static string line; if (!getline(cin, line)) return 0; stringstream ss(line); int v; a.clear(); while (ss >> v) a.push_back(v); return a.size(); } Node *root = NULL; void remove_tree(Node *u) { if (!u) return; remove_tree(u->left); remove_tree(u->right); delete u; } Node *build_tree(int l, int r, int ll, int rr) { Node *ret = new Node(post_order[rr]); int p = l; int cnt = 0; while (in_order[p] != ret->val) { p++; cnt++; } if (cnt > 0) ret->left = build_tree(l, l+cnt-1, ll, ll+cnt-1); if (rr-1 >= ll+cnt) ret->right = build_tree(p+1, r, ll+cnt, rr-1); return ret; } int min_sum; int best_val; void _dfs(Node *u, int sum) { sum += u->val; if (!u->left && !u->right) { if (sum < min_sum || (sum == min_sum && u->val < best_val)) { min_sum = sum; best_val = u->val; } return; } 4000 if (u->left) _dfs(u->left, sum); if (u->right) _dfs(u->right, sum); } int main() { int n; while (n = read_list(in_order)) { read_list(post_order); remove_tree(root); root = build_tree(0, n-1, 0, n-1); min_sum = best_val = SUP; _dfs(root, 0); printf("%d\n", best_val); } return 0; }
相关文章推荐
- Uva548——Tree
- Tree UVA - 548
- uva 548 tree
- 二叉树 UVA 548 Tree
- UVa 548 - Tree
- 【日常学习】【二叉树遍历】Uva548 - Tree题解
- uva 548 Tree
- 例题6-8 UVa548 Tree(树的遍历转换)
- UVa548 Tree(递归链表的结合)
- uva 548 - Tree
- UVa 548 Tree(建树,递归遍历)
- uva 548 - Tree
- UVA 548 Tree(数据结构,二叉树,遍历)
- UVA_548: Tree
- Tree(uva 548)
- uva_ 548-Tree
- UVa 548 Tree (中序遍历&后序遍历&DFS)
- UVa 548 - Tree【二叉树的递归遍历(DFS)】
- UVa 548 - Tree
- UVA 548 Tree