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
Miguel A. Revilla
1999-01-11
输入:输入有多组,对于每一组输入,第一行为一棵二叉树的中序遍历,第二行为其后序遍历。
输出:问你找出一条从跟到叶子节点权重和最小的路径。并打印其叶子节点(有多种答案,则打印叶子节点值最小的)。
解法:依照所给中序和后续遍历,建一棵二叉树。然后遍历这棵树。用一个best来保存叶子节点的值 ,bestsum来保存和。递归到叶子节点是就比较更新答案 。最后打印答案即可。
总结:对于任意一棵二叉树,给定其中序遍历和后续遍历(前序遍历也行)可以构造这棵二叉树。我们可以首先从后序(前序)遍历中找到根节点,然后再在中序遍历中找到这个点,他左边的就是他左子树的点,右边即位右子树的点。如此递归,直到找到叶子节点。然后回溯保存根节点即可。
AC代码:
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stack>
#include<algorithm>
#include<sstream>
using namespace std;
#define maxn 105000
#define ll __int64
int xx,n;
int in_order[maxn],post[maxn],lch[maxn],rch[maxn];/*in_order存的是中序遍历,post存的后续遍历,lch[i]表示节点i的左左儿子,rch[i]表示节点i的右儿子*/
int read_in(int *a)//读入函数
{
string line;
n=0;
if(!getline(cin,line)) return false;//读一行输入
stringstream ss(line);
while(ss>>xx)
{
a[n++]=xx;
//cout<<xx<<' ';
} ;//将字符串转换为整数,并存入数组
//cout<<endl;
return n>0;
}
int build(int l1,int r1,int l2,int r2)//建树函数
{
if(l1>r1) return 0;//为空时
int root=post[r2];//从后续遍历中找到跟节点
int p=l1;//p,在中序遍历中从起始位置开始找到根节点
while(in_order[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;//返回根节点
}
int best ,best_sum;
void dfs(int u,int sum)//遍历函数
{
sum+=u;
if(!lch[u]&&!rch[u])//找到叶子节点并处理
{
if(sum<best_sum||(sum==best_sum&&u<best))
{
best=u;best_sum=sum;
}
}
if(lch[u]) dfs(lch[u],sum);//遍历其左子树
if(rch[u]) dfs(rch[u],sum);//遍历其右子树
}
int main()
{
memset(lch,0,sizeof(lch));
memset(rch,0,sizeof(rch));
while(read_in(in_order))
{
read_in(post);
build(0,n-1,0,n-1);
best_sum=1000000000,best=10100;
dfs(post[n-1],0);
cout<<best<<endl;
}
return 0;
}