您的位置:首页 > 其它

指针建树uva548

2014-03-01 20:21 375 查看
题意:给出中序遍历和后序遍历,找出最短路径上的叶结点的值

思路:先建树然后dfs找

#include<iostream>
#include<cstdio>
#include<string>
#include<sstream>
#include<cstring>
#include<vector>
using namespace std;
struct node
{
    int data;
    node *left,*right;
    node()
    {
        data=0;
        left=right=NULL;
    }
};
const int INF=1000000000;
const int maxn=10010;
int inorder[maxn],postorder[maxn],n,max1;
vector<int> result;
vector<node *>pos;
node * build_tree(int len,int *in,int *po)
{
    if(len<=0)return NULL;
    int i=len-1;
    while(po[len-1]!=in[i])i--;
    node *f=new node();
    f->data=po[len-1];
    f->left=build_tree(i,in,po);
    f->right=build_tree(len-1-i,in+i+1,po+i);
    return f;
}
void dfs(node *p,int sum)
{
    if(!p->left&&!p->right)
    {
        result.push_back(sum+p->data);
        pos.push_back(p);
        return;
    }
    if(p->left)dfs(p->left,sum+p->data);
    if(p->right)dfs(p->right,sum+p->data);
}
int main()
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
    #endif

    string s;
    while(scanf("%d",&inorder[0])!=EOF)
    {
        n=1;
        while(getchar()!='\n')
            cin>>inorder[n++];
        for(int i=0;i<n;i++)
        cin>>postorder[i];

        node *root=build_tree(n,inorder,postorder);

        result.clear();
        pos.clear();
        dfs(root,0); //cout<<n<<endl;
        int max1=INF,ans;
        for(int i=0;i<result.size();i++)
            if(result[i]<max1){ans=i;max1=result[i];}
        cout<<pos[ans]->data<<endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: