首页 > 代码库 > uva 548 Tree
uva 548 Tree
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
Miguel A. Revilla
1999-01-11
题目大意:
给定一个二叉树的中序和后序遍历,求二叉树到每个叶节点的路径和最小的那个叶节点的值。
解题思路:
先建树,后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; }
补充:
在任一给定结点上,可以按某种次序执行三个操作:
⑴访问结点本身(N),
⑵遍历该结点的左子树(L),
⑶遍历该结点的右子树(R)。
根据访问结点操作发生位置命名:
① NLR:前序遍历(PreorderTraversal亦称(先序遍历))
——访问结点的操作发生在遍历其左右子树之前。
② LNR:中序遍历(InorderTraversal)
——访问结点的操作发生在遍历其左右子树之中(间)。
③ LRN:后序遍历(PostorderTraversal)
——访问结点的操作发生在遍历其左右子树之后。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。