UVa 548 - Tree
2014-03-10 09:43
239 查看
Tree |
nodes along that path.
Input
The input file will contain a description of the binary tree given as the inorder and postorder traversal sequences of that tree. Your program will read two line (until end of file) from the input file. The firstline will contain the sequence of values associated with an inorder traversal of the tree and the second line will contain the sequence of values associated with a postorder traversal of the tree. All values will be different, greater than zero and less than
10000. You may assume that no binary tree will have more than 10000 nodes or less than 1 node.
Output
For each tree description you should output the value of the leaf node of a path of least value. In the case of multiple paths of least value you should pick the one with the least value on the terminal node.Sample Input
3 2 1 4 5 7 6 3 1 2 5 6 7 4 7 8 11 3 5 16 12 18 8 3 11 7 16 18 12 5 255 255
Sample Output
1 3 255
Miguel A. Revilla
1999-01-11
#include <iostream> #include <cstring> #include <string> #include <cstdlib> #include <cstdio> using namespace std; const int MAX = 1000000+5; int in[MAX], aft[MAX]; int ans=1e9; long long sum=0, min_sum=1e9; bool l,r; bool preOrder(int *in, int *aft, int length, int sum) { if(length==0) return true; sum += *(aft+length-1); int index=0; for(; index < length; index++) { if(in[index]==*(aft+length-1)) break; } l = preOrder(in, aft, index, sum);// 无左树 // 无右树 r = preOrder(in+index+1, aft+index, length-index-1, sum); if(l&&r){ if(sum < min_sum) { min_sum = sum; ans =*(aft+length-1); }else if(sum==min_sum) ans = min(ans, *(aft+length-1)); } return false; } int min(int a, int b) { return a<b?a:b; } int convertData(char *s, int *v) { int top=0; for(int i=0;s[i];i++) { while(s[i]==' ') i++; v[top]=0; while(s[i]&&isdigit(s[i])) { v[top]=v[top]*10+s[i]-'0'; i++; } top++; if(!s[i]) break; } return top; } void init() { sum=0; ans = 1e9; min_sum=1e9; } int main() { // freopen("in.txt","r",stdin); char ch[MAX]; while(cin.getline(ch, sizeof(ch))) { init(); int length = convertData(ch, in); cin.getline(ch, sizeof(ch)); convertData(ch, aft); preOrder(in, aft, length, 0); cout << ans << endl; } return 0; }
相关文章推荐
- UVA - 548 Tree
- uva 548 -Tree
- 【日常学习】【二叉树遍历】Uva548 - Tree题解
- uva 548 Tree(通过后序,先序重建树+dfs)
- UVa548 Tree(递归链表的结合)
- (二叉树)UVA - 548 Tree
- Tree UVA 548(DFS)
- uva 548 tree
- 二叉树 UVA 548 Tree
- uva 548 - Tree
- UVa 548 - Tree
- UVA 548 Tree
- UVa 548 (二叉树的递归遍历) Tree
- UVa 548 - Tree
- uva548 tree
- UVA 548 Tree
- UVA548 - Tree
- uva 548 Tree (根据中序遍历和后序遍历求先序遍历)
- UVA 548 Tree 中序+后序构造二叉树dfs
- uva 548 Tree