UVa 548 Tree(二叉树最短路径)

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

题意

已知中序和后序,求叶节点到根节点的最短路径,若相同则叶节点小的优先,输出叶节点

题解

bfs找统计最优解就不说了,这是用递归做的

代码

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int Left[10005],Right[10005],In[10005],Post[10005];
 4 int n,best,best_sum;
 5 //把In[L1,R1],Post[L2,R2]建树
 6 int build(int L1,int R1,int L2,int R2,int sum)
 7 {
 8     if(L1>R1)return 0;//空树
 9     int root=Post[R2];//后序最后一个节点为根
10     sum+=root;
11     int p=L1;//中序的头开始找根
12     while(In[p]!=root)p++;
13     int cnt=p-L1;//左子树个数
14     if(L1>p-1&&p+1>R1)//叶节点
15     {
16         if(sum<best_sum||(sum==best_sum&&root<best))
17         {
18             best=root;
19             best_sum=sum;
20         }
21     }
22     Left[root]=build(L1,p-1,L2,L2+cnt-1,sum);
23     Right[root]=build(p+1,R1,L2+cnt,R2-1,sum);
24     return root;//返回树根给左子树或右子树
25 }
26 int read(int *a)
27 {
28     string s;
29     if(!getline(cin,s))return 0;
30     stringstream ss(s);
31     int x;
32     n=0;
33     while(ss>>x)a[n++]=x;
34     return 1;
35 }
36 int main()
37 {
38     while(read(In))
39     {
40         read(Post);
41         best_sum=1e9;
42         build(0,n-1,0,n-1,0);
43         printf("%d\n",best);
44     }
45     return 0;
46 }

 

posted on 2018-02-23 15:33  大桃桃  阅读(290)  评论(0编辑  收藏  举报

导航