Tree, Uva 548
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
分析
后序遍历的第一个字符就是根结点,因此只需在中序遍历中找到它,就知道左右子树的中序和后序遍历了。
这样可以先把二叉树构造出来,然后再执行一次递归遍历,找到最优解。
public class TreeDFS {
static int maxv = 10000 + 10;
static int[] inOrder;// 中序遍历序列
static int[] postOrder;// 后序遍历序列
static int[] lch;// 对应结点的左子节点
static int[] rch;// 对应结点的右子节点
static int best;// 最优解
static int bestSum;// 目前为止最优解对应的权和
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String[] line = sc.nextLine().split(" ");
inOrder = readNode(line);// 中序遍历
line = sc.nextLine().split(" ");
postOrder = readNode(line);// 后序遍历
lch = new int[maxv];
rch = new int[maxv];
int root = build(0, inOrder.length - 1, 0, postOrder.length - 1);
bestSum = 1000000000;
dfs(root, 0);
System.out.println(best);
}
sc.close();
}
private static void dfs(int u, int sum) {
// TODO 查找权值最优解 ---- u 当前结点的权值
sum += u;
if (lch[u] == 0 && rch[u] == 0) {// 当某结点没有左右子结点,则该结点为叶子
if (sum < bestSum || (sum == bestSum && u < best)) {
best = u;
bestSum = sum;
}
}
if (lch[u] != 0) {
dfs(lch[u], sum);
}
if (rch[u] != 0) {
dfs(rch[u], sum);
}
}
private static int build(int L1, int R1, int L2, int R2) {
// TODO 建立二叉树,返回树的根结点的值
if (L1 > R1) {
return 0;// 空树
}
int root = postOrder[R2];
int p = L1;
while (inOrder[p] != root) {
p++;
}
int cnt = p - L1;// 左子树的结点个数
lch[root] = build(L1, p - 1, L2, L2 + cnt - 1);
rch[root] = build(p + 1, R1, L2 + cnt, R2 - 1);
return root;
}
private static int[] readNode(String[] line) {
// TODO 读取遍历序列
int[] order = new int[line.length];
for (int i = 0; i < order.length; i++) {
int nodeVal = Integer.parseInt(line[i]);
order[i] = nodeVal;
}
return order;
}
}