Tree
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
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
研究了3天的二叉树,只为做这一道题目,不过基本算法一遍就过,也真是皇天不负有心人呀。
题意:给出二叉树的中序序列和后序序列,然后找出权值最小的路径的叶子结点的权值。
首先,根据中序序列和后序序列建树这里就不多说了,具体的做法见挂在树上的兔子,然后就是找路径权值最小,这里就需要先序遍历二叉树,才开始读错题意了,以为只是查找权值最小的节点,就这样赤裸裸地WA了一遍。
稍微做了一点处理,代码就出炉了,具体来看吧:
#include <stdio.h>
#include <string.h>
typedef struct jie
{
int data;
struct jie *lch;
struct jie *rch;
} BiTNode,*BiTree;
void creatBiTree(BiTree &T,int *ins,int *post,int len)
{
if(len == 0)
{
T = NULL;
return ;
}
T = new BiTNode;
T ->data = *(post+len-1);
int i = 0;
for(i; i < len; i++)
{
if(ins[i] == *(post+len-1))
break;
}
creatBiTree(T->lch,ins,post,i);
creatBiTree(T->rch,ins +i + 1,post+i,len-i-1);
}
void valueBiTree(BiTree &T,int &sum,int &minn,int &smin)
{
sum += T->data;//记录当前路径的总权值
if(T->lch == NULL && T->rch == NULL)
{
if(smin > sum)//比较当前路径权值和记录下的最短路径权值,做相应操作
{
smin = sum;
minn = T->data;
}
}
if(T->lch) valueBiTree(T->lch,sum,minn,smin);
if(T->rch) valueBiTree(T->rch,sum,minn,smin);
sum = sum - T->data;//退出某个节点,权值相应的减少
}
int main()
{
int ins[10009],post[10009];
int i;
char j;
while(~scanf("%d",&ins[0]))
{
scanf("%c",&j);
if(j != '\n')
for( i = 1; i < 10009; i++)
{
scanf("%d",&ins[i]);
scanf("%c",&j);
if(j == '\n')
break;
}
for( i = 0; i < 10009; i++)
{
scanf("%d",&post[i]);
scanf("%c",&j);
if(j == '\n')
break;
}
BiTree head;
int smal = 99999;
int sum = 0,smin = 99999;
creatBiTree(head,ins,post,++i);
valueBiTree(head,sum,smal,smin);
printf("%d\n",smal);
}
return 0;
}