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.
Input
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.
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
题意:给你一个数的中序遍历和后序遍历。然后从这个数的根节点开始,一直到叶子结束算一条路径。让你求最短的路径,如果路径相同,则选择叶子较小的。
想法:我们知道,如果知道一个数的中序遍历,然后在先序和后序中任意选取一个。便可以将二叉树重建起来。
那么二叉树的建立和重建其实都用到了递归的思想。就比如这道题目给了中序遍历和后序遍历。那么我们先在后序中找到最后一个元素,一定是这棵树的根节点,然后在中序遍历中找到该节点,那么位于左边的一定是左子树,右边为右子树。然后按照递归的方式继续建立,知道所有的结点都放到了重建的树上,那么二叉树便是建立完成了。
之后只要按照任意先中后任意一种遍历得到叶子结点的信息和路径长度就算是搞定这道题了。
由于是自己自学数据结构的,还没开始上课。所有学起来比较的慢,不过总算是把树基本的东西搞得差不多了。
#include<iostream>
#include<cstdio>
#include<cstdlib>
int mins=1<<30,minv=1<<30;
using namespace std;
struct node
{
int v;
int sum;
node* lchild;
node* rchild;
};
int in[10010],post[10010],pre[10010];
node* build(int n, int *post, int *in, node *u, int s)
{
int i=0;
if (n<=0) return NULL;
while(*(in+i)!=*post) i++;
u=(node*) malloc (sizeof(node));
u->v=*(in+i);
u->sum=s+u->v;
u->lchild=build(i,post-n+i,in,u->lchild,u->sum);
u->rchild=build(n-i-1,post-1,in+i+1,u->rchild,u->sum);
if (u->lchild==NULL && u->rchild==NULL && u->sum<=mins)
{
if (mins>u->sum)
{
mins=u->sum;
minv=u->v;
}
else if (u->v<minv)
{
minv=u->v;
}
}
return u;
}
void preorder(node* u)
{
if (u!=NULL)
{
cout<<u->v<<" "<<u->sum<<" ";
preorder(u->lchild);
preorder(u->rchild);
}
}
int main ()
{
int t,ni=0,i;
char ch;
while(scanf("%d",&t)!=EOF)
{
ch=getchar();
in[ni++]=t;
if (ch=='\n')
{
mins=minv=1<<30;
for (i=0; i<ni; i++)
cin>>post[i];
node* root;
root=build(ni,post+ni-1,in,root,0);
//preorder(root);
//cout<<endl;
cout<<minv<<endl;
ni=0;
}
}
return 0;
}