您的位置:首页 > 理论基础 > 数据结构算法

【暑假】[基本数据结构]根据in_order与post_order构树

2016-03-30 17:19 239 查看
Tree

Time Limit: 3000MSMemory Limit: Unknown64bit IO Format: %lld & %llu
Submit Status

Description



You are to determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root of the binary tree to any leaf. The value of a path is the sum of values of 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 first line 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

-------------------------------------------------------------------------------------------------------------------------------------------------------

算法:pre_order|post_order寻找根节点,in_order判断左右子树,递归处理。DFS to find_ans


1 #include<iostream>
2 #include<cstdio>
3 #include<sstream>
4 #include<algorithm>
5 #define FOR(a,b,c) for(int a=(b);a<(c);a++)
6 using namespace std;
7
8 const int maxn = 10000 + 10,INF=1<<30;
9 int in_order[maxn],post_order[maxn],lch[maxn],rch[maxn];
10 int n,best,ans,root;
11
12 int read_list(int* a){
13     string line;
14     if(!getline(cin,line)) return false;
15     stringstream ss(line);
16     n=0;
17     int x;
18     while(ss>>x) a[n++]=x;
19     return n>0;
20 }
21
22 int build_tree(int L1,int R1,int L2,int R2){
23     if(R1<L1) return 0;
24     int root=post_order[R2];
25     int p=L1;
26     while(in_order[p] != root) p++;
27     int cnt=p-L1;
28     lch[root]=build_tree(L1,p-1,L2,L2+cnt-1);
29     rch[root]=build_tree(p+1,R1,L2+cnt,R2-1);
30     return root;
31 }
32
33 void dfs(int u,int cnt){
34     cnt += u;
35     if(cnt>ans) return;
36     if(!lch[u] && !rch[u])
37       if(cnt<ans || (cnt==ans && best<u)){ ans=cnt; best=u;}
38     if(lch[u]) dfs(lch[u],cnt);
39     if(rch[u]) dfs(rch[u],cnt);
40 }
41
42 int main(){
43     while(read_list(in_order)){
44         read_list(post_order);
45         build_tree(0,n-1,0,n-1);
46         ans=INF;
47         dfs(post_order[n-1],0);
48         cout<<best<<endl;
49     }
50     return 0;
51 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: