紫书章六例题八 UVA 548 (中序后序建树,前序遍历求值)
2017-04-15 12:12
375 查看
#include <iostream> #include <cstring> #include <algorithm> #include <cstdio> #include <sstream> using namespace std; int in_order[10005],pre_order[10005]; struct node { int data; node *l,*r; node(int a=0,node *left=NULL,node *right=NULL){ data=a,l=left,r=right; } }; node *root; node* buildtree(int li,int ri,int lp,int rp)//中序,后序 { if(li>ri||lp>rp) return NULL; node *t=new node(); t->data=pre_order[lp]; int cur=li; while(in_order[cur]!=t->data) cur++; int cnt=cur-li; t->l=buildtree(li,cur-1,rp-cnt+1,rp); t->r=buildtree(li+cnt+1,ri,lp+1,rp-cnt); return t; } int maxn=100000001,ans=0; void qx(node *t,int v,int sum) { if(t->l==NULL&&t->r==NULL){ if(sum<maxn) {maxn=sum;ans=v;} } if(t->l!=NULL) qx(t->l,t->l->data,sum+t->l->data); if(t->r!=NULL) qx(t->r,t->r->data,sum+t->r->data); } void remove_tree(node *t) { if(t == NULL) return ; remove_tree(t->l); remove_tree(t->r); delete t; } int main() { string str; int num=1,h=0; while(getline(cin,str)) { stringstream ss(str); int x; if(num==1){ while(ss>>x) in_order[h++]=x; num=2; } else if(num==2) { int temp=h; while(ss>>x) pre_order[--temp]=x; root=new node(); root=buildtree(0,h-1,0,h-1); num=1; qx(root,root->data,0); printf("%d\n",ans); remove_tree(root); ans=0;maxn=100000001;h=0; memset(in_order,0,sizeof(in_order)); memset(pre_order,0,sizeof(pre_order)); } } return 0; }
相关文章推荐
- 紫书章六例题八 UVA 548 (中序后序建树,前序遍历求值)
- 紫书章六例题八 UVA 548 (中序后序建树,前序遍历求值)
- 紫书章六例题八 UVA 548 (中序后序建树,前序遍历求值)
- 紫书章六例题八 UVA 548 (中序后序建树,前序遍历求值)
- 紫书章六例题八 UVA 548 (中序后序建树,前序遍历求值)
- 紫书章六例题八 UVA 548 (中序后序建树,前序遍历求值)
- 紫书章六例题八 UVA 548 (中序后序建树,前序遍历求值)
- 紫书章六例题10 下落的树叶 UVA 699 (根据前序遍历建树)
- 紫书章六例题10 下落的树叶 UVA 699 (根据前序遍历建树)
- 紫书章六例题10 下落的树叶 UVA 699 (根据前序遍历建树)
- Uva548 Tree 【递归建树+dfs遍历树】【例题6-8】
- 紫书章六例题10 下落的树叶 UVA 699 (根据前序遍历建树)
- 紫书章六例题10 下落的树叶 UVA 699 (根据前序遍历建树)
- 紫书章六例题10 下落的树叶 UVA 699 (根据前序遍历建树)
- 紫书章六例题10 下落的树叶 UVA 699 (根据前序遍历建树)
- 紫书章六例题10 下落的树叶 UVA 699 (根据前序遍历建树)
- uva548 Tree +二叉树用中序和后序建树
- UVa 548 Tree 根据后序遍历和中序遍历建树后DFS
- 548 - Tree uva - 深搜 + 建树
- 紫书章六例题16 单词 UVA 10129(欧拉道路)