题目如下:
Tree
Tree |
You are to determine the value of the leaf node in a given binary treethat is the terminal node of a path of least value from the root of thebinary tree to any leaf. The value of a path is the sum of values of nodesalong that path.
Input
The input file will contain a description of the binary tree given as theinorder and postorder traversal sequences of that tree. Your program willread two line (until end of file) from the input file. The first line willcontain the sequence of values associated with an inorder traversal of thetree and the second line will contain the sequence of values associatedwith 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 shouldoutput the value of the leaf node of a path of least value. In the case ofmultiple 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
现根据中序和后序建树,再先序遍历树,对每个叶子节点,既要保存当前的和,又要保存当前的叶子节点。
AC的代码如下:
#include
using namespace std;
struct BINTREE
{
int data;
BINTREE*lchild,*rchild;
};
typedef struct ans
{
int sum;
int leaf;
} ANS;
vector
A;
int cmp(const ANS&p,const ANS&q)
{
if(p.sum
lchild = NULL;
u -> rchild = NULL;
}
BINTREE* InPostCreateTree(int *mid , int *post , int len)
{
if(len == 0)
return NULL;
int i = len-1;
while(post[len-1] != mid[i])
--i;
BINTREE *root = new BINTREE;
newBtree(root);
root -> data = post[len-1];
root -> lchild = InPostCreateTree(mid,post,i);
root -> rchild = InPostCreateTree(mid+i+1,post+i,len-i-1);
return root;
}
void traveltree(BINTREE*T,int sum)
{
if(!T)
return;
sum+=T->data;
if(!T->lchild&&!T->rchild)
{
ANS a;
a.sum=sum;
a.leaf=T->data;
A.push_back(a);
}
if(T->lchild) traveltree(T->lchild,sum);
if(T->rchild) traveltree(T->rchild,sum);
}
int main()
{
int s1[10010],s2[10010],i=0,j=0,v=0,number=0;
char c;
while(scanf("%c",&c)!=EOF)
{
if(isdigit(c))
v=v*10+c-'0';
else if(c==' ')
{
if(!number)
{
s1[i++]=v;
v=0;
}
else
{
s2[j++]=v;
v=0;
}
}
else if(c=='\n')
{
if(!number)
{
s1[i++]=v;
v=0;
}
else
{
s2[j++]=v;
v=0;
traveltree(InPostCreateTree(s1,s2,i),0);
int minsum=99999999,minleaf;
for(int k=0; k