标签:des style class blog c code
| 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.
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
1 3 255
题目大意:
给定一个二叉树的中序和后序遍历,求二叉树到每个叶节点的路径和最小的那个叶节点的值。
解题思路:
先建树,后dfs,建树也就是后序的最后一个就是二叉树的当前节点的值,再在中序中找到这个值,那么左边就是左子树,右边就是又子树,再从后序中找出相应的左右子树的后序,然后划分为子问题递归求解。
解题代码:
#include <iostream>
#include <cstdio>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
struct node{
int c;
node *l,*r;
node(){l=NULL;r=NULL;}
};
vector <int> v;
node* build(vector <int> vIn,vector <int> vPost){
int s=0;
node *tree=new node();
vector <int> lIn,rIn;
vector <int> lPost,rPost;
tree->c=vPost.back();
while(vIn[s]!=tree->c){
lIn.push_back(vIn[s]);
lPost.push_back(vPost[s]);
s++;
}
if(lIn.size()>0) tree->l=build(lIn,lPost);
for(int i=s+1;i<vIn.size();i++){
rIn.push_back(vIn[i]);
rPost.push_back(vPost[i-1]);
}
if(rIn.size()>0) tree->r=build(rIn,rPost);
return tree;
}
void dfs(node *p,int sum){
if(p->l==NULL && p->r==NULL ){
v.push_back(sum+(p->c));
v.push_back(p->c);
}
if(p->l!=NULL) dfs(p->l,sum+(p->c));
if(p->r!=NULL) dfs(p->r,sum+(p->c));
}
int main(){
string str1,str2;
while(getline(cin,str1) && getline(cin,str2)){
int x;
vector <int> vIn,vPost;
stringstream ss1(str1),ss2(str2);
while(ss1>>x) vIn.push_back(x);
while(ss2>>x) vPost.push_back(x);
node *tree=new node();
tree=build(vIn,vPost);
v.clear();
dfs(tree,0);
int sum=1e9,ans=-1;
for(int i=0;i<v.size();i+=2){
if(v[i]<sum){
sum=v[i];
ans=v[i+1];
}
}
cout<<ans<<endl;
}
return 0;
}
补充:
标签:des style class blog c code
原文地址:http://blog.csdn.net/a1061747415/article/details/26278575