二叉树的最小路径
描述
给一棵结点带权(权值各不相同,都是小于1000的正整数)的二叉树的中序和后序遍历,找一个叶子使得它到根的路径上的权值和最小。如果有多解,该叶子本身的权值应该尽量小。
输入
输入包含多组数据,每组有两行,其中第一行为中序遍历,第二行为后序遍历
输出
对每组数据输出符合答案的叶子节点的权值
样例输入
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
样例输出
1
3
255
#include <cstdio>
#include <cstdlib>
#include <cstring>
const int INF = 1000000;
struct node { // 二叉树结点
int data; // 数据域
node* left; // 左孩子
node* right; // 右孩子
};
node* build(int* in, int* post, int il, int ih, int pl, int ph) {
// 根据中序遍历in[il, ih]和后序遍历post[pl, ph]构造二叉树
if(il>ih) { // 空树
return NULL;
}
node* root = (node*)malloc(sizeof(node)); // 根节点
root->data = post[ph];
// 在中序遍历中寻找根节点,然后划分左右子树
int rootInd = il;
while(in[rootInd] != root->data) rootInd++;
int llen = rootInd