UVAOJ548

Written by    21:01 January 3, 2015 

UVAOJ548

548 – Tree

Time limit: 3.000 seconds

  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 

Sample Output 


Miguel A. Revilla
1999-01-11

给出同一颗树的中序遍历和后序遍历, 树中每一个节点的值都唯一, 然后求最短路径的叶子, 如果有多条最短路径的话就输出最小的叶子.

这里就直接DFS, 然后遍历到了叶子过后就比较路径或者叶子大小.

在已知中序和后序遍历的时候, 如下:

中序 D B G E A C F

后序 D G E B F C A

有以下的特点, 首先后序遍历最后一个节点A必然是树的根节点, 然后在中序遍历中, A的左边必然是A左边子树, 右边必然是右边子树.
然后A在后续遍历中左边第一个节点必然是A的右儿子.

那么如何确定左儿子呢?

后序遍历中根永远是最后一个访问, 所以A在后续遍历中前面的要么是左边子树, 要么是右边子树, 由中序遍历可知D G B E在A的左边, F C在A的右边, 在后续遍历中最靠近A的左边子树成员即是A的左儿子, 然后还可以发现A的左边子树和右边子树在后续遍历中不会交叉, 所以如果知道A的子树节点个数的话就可以直接求出左儿子.

虽然卡了三天的WA, 但是最终还是好好巩固了一下树的遍历, anyway, failure is also processing.

Category : acmstudy

Tags :