您的位置:首页 > 其它

紫书章六例题八 UVA 548 (中序后序建树,前序遍历求值)

2017-04-15 12:12 337 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: