uva 558 tree(不忍吐槽的题目名)——yhx

本文介绍了一种算法,用于确定二叉树中从根到叶子节点路径的最小累积值,并找出该路径末端的叶子节点值。输入包括二叉树的中序遍历和后序遍历序列,通过递归构建二叉树并使用深度优先搜索来解决。
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.

 1 #include<cstdio>
 2 #include<cstring>
 3 struct node
 4 {
 5     int lch,rch;
 6 }a[10010];
 7 int zx[10010],hx[10010],n,ans=0x7f7f7f7f,ans_leaf=0x7f7f7f7f;
 8 bool rdzx()
 9 {
10     int i,j,k,p,q,x,y,z;
11     char c;
12     if (scanf("%d",&zx[1])==-1) return 0;
13     n=1;
14     while (scanf("%c",&c)&&c==' ')
15       scanf("%d",&zx[++n]);
16     return 1;
17 }
18 void rdhx()
19 {
20     int i;
21     for (i=1;i<=n;i++)
22       scanf("%d",&hx[i]);
23 }
24 int crt(int lz,int rz,int lh,int rh)
25 {
26     if (lz>rz) return 0;    //注意终止条件
27     int i,j,k,p,q,x,y,z;
28     p=hx[rh];
29     i=lz;
30     while (zx[i]!=p) i++;
31     a[p].lch=crt(lz,i-1,lh,i+lh-lz-1);   //关键在于这两个式子的推导,列方程求比较不费脑子
32     a[p].rch=crt(i+1,rz,rh-rz+i,rh-1);
33     return p;
34 }
35 void sc(int p,int x)
36 {
37     int i,j,k,l,m,y,z;
38     x+=p;
39     if (!a[p].lch&&!a[p].rch)
40     {
41         if (x<ans||(x==ans&&p<ans_leaf))
42         {
43             ans=x;
44             ans_leaf=p;
45             return;
46         }
47     }
48     if (a[p].lch) sc(a[p].lch,x);
49     if (a[p].rch) sc(a[p].rch,x);
50 }
51 int main()
52 {
53     int i,j,k,l,m,p,q,x,y,z;
54     while (rdzx())
55     {
56         rdhx();
57         memset(a,0,sizeof(a));
58         crt(1,n,1,n);
59         ans=ans_leaf=0x7f7f7f7f;
60         sc(hx[n],0);
61         printf("%d\n",ans_leaf);
62     }
63 }

递归求树,由于后序遍历的最后一个元素一定是根,所以可以在中序中找到根的位置,则其左边为左子树,右边为右子树,分治求解。

求值相对简单,dfs即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值