题目地址:点击打开链接
In the case of multiple paths of least value you should pick the one with the least value on the terminal node.
这个地方真是古怪,被注释起来的代码错了,改成下面就好了,略蛋疼!
C++代码:
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <limits>
using namespace std;
vector<int> inOrder,postOrder;
int maxNum,x,sum;
struct TreeNode
{
int data;
TreeNode *left,*right;
};
TreeNode *build(int inBegin,int inEnd,int postBegin,int postEnd)
{
if(inBegin<=inEnd&&postBegin<=postEnd)
{
vector<int>::iterator itr=find(inOrder.begin()+inBegin,inOrder.begin()+inEnd+1,postOrder[postEnd]);
int dis=itr-inOrder.begin();
TreeNode *p=new TreeNode;
p->data=*itr;
p->left=build(inBegin,dis-1,postBegin,postBegin+dis-1-inBegin);
p->right=build(dis+1,inEnd,postBegin+dis-inBegin,postEnd-1);
return p;
}
else
return NULL;
}
void preOrderTra(TreeNode *head)
{
if(head)
{
sum+=head->data;
if(head->left==NULL&&head->right==NULL)
{
/*if(sum<=maxNum)
{
maxNum=sum;
if(x>head->data)
x=head->data;
}*/
if(sum<maxNum)
{
maxNum=sum;
x=head->data;
}
}
preOrderTra(head->left);
preOrderTra(head->right);
sum-=head->data;
}
}
int main()
{
string s1,s2;
while(getline(cin,s1))
{
maxNum=numeric_limits<int>::max();
x=maxNum;
sum=0;
getline(cin,s2);
inOrder.clear();
postOrder.clear();
istringstream input1(s1);
int data;
while(input1>>data)
inOrder.push_back(data);
istringstream input2(s2);
while(input2>>data)
postOrder.push_back(data);
TreeNode *head=build(0,inOrder.size()-1,0,postOrder.size()-1);
preOrderTra(head);
cout<<x<<endl;
}
return 0;
}