UVA 548(超详细解答,无需dfs)

这篇博客介绍了如何解决UVA 548问题,即给定一棵二叉树的中序和后序遍历,找到路径权值最小的叶子节点。解题思路是不需要重建二叉树,而是通过递归过程直接找到答案。通过分析中序和后序遍历的特性,确定根节点位置,并分割左右子树。最后提供了代码实现并给出了注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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
output
1
3
255

题目要求

本题的输入是一颗二叉树的中序遍历和后序遍历,要求找出一个叶子节点使得它到根节点的路径权值最小,如果有多条路径权值相同,那么输出叶节点本身权值最小的节点。

解题思路

1:首先介绍一般思路,由中序遍历和后序遍历可以通过递归函数来重新构建二叉树。然后通过dfs搜索求出答案。
2:无需重新构建二叉树,然后在进行搜索,可以在递归的过程中直接求出答案。
以下是详细解答:
以题目中的第一次输入为例:
3 2 1 4 5 7 6
3 1 2 5 6 7 4
我们知道,中序遍历的顺序是左子树->根节点->右子树
而后序遍历的顺序是左子树->右子树->根节点,
从中我们发现后序遍历中的最右边那个数就是整棵树的根节点。
question1:那么如何将这棵树分为左子树和右子树呢?
ans:通过中序遍历,在中序遍历中找到后序遍历中最右边数的下标,以该下标为分界线,就可以分出左右子树.
question2:中序遍历分割为左右子树很简单,那么后序遍历如何完成这样的同步分割呢?
ans:通过观察可以发现,中序遍历和后序遍历的前两个部分是相同的,都是由左子树->根节点,我们可以知道,只要将我们在第一步中求出的根节点下标减一就是左子树的右边界线。而将后序遍历数组的最后一位向左边移动一位就是右子树的右边界.
下面是演示图:

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我还是忘不了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值