题目
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:通过观察可以发现,中序遍历和后序遍历的前两个部分是相同的,都是由左子树->根节点,我们可以知道,只要将我们在第一步中求出的根节点下标减一就是左子树的右边界线。而将后序遍历数组的最后一位向左边移动一位就是右子树的右边界.
下面是演示图: