PAT (Advanced Level) 1086. Tree Traversals Again (25)

入栈顺序为先序遍历,出栈顺序为中序遍历。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<stack>
using namespace std;

const int maxn=1000+10;
const int INF=0x7FFFFFFF;
int n,tot;
int Preorder[maxn],Inorder[maxn],Postorder[maxn];
int APreorder[maxn],AInorder[maxn];
int ans[maxn];
struct Binary_Tree
{
    int left;
    int right;
    int date;
} node[maxn];
int p1,p2;
stack<int>s;

void Build_Binary_Tree(int L,int R,int father)
{
    int i,MIN=INF,MAX=-INF;
    for(i=L; i<=R; i++)
    {
        if(APreorder[Inorder[i]]>MAX) MAX=APreorder[Inorder[i]];
        if(APreorder[Inorder[i]]<MIN) MIN=APreorder[Inorder[i]];
    }
    node[tot].date=Preorder[MIN];
    if(father<0) node[-father].right=tot;
    if(father>0) node[father].left=tot;
    int now=tot;
    tot++;
    if(AInorder[Preorder[MIN]]-1-L>=0)
        Build_Binary_Tree(L,AInorder[Preorder[MIN]]-1,now);
    if(R-(AInorder[Preorder[MIN]]+1)>=0)
        Build_Binary_Tree(AInorder[Preorder[MIN]]+1,R,-now);
}

void dfs(int p)
{
    if(node[p].left!=-1) dfs(node[p].left);
    if(node[p].right!=-1) dfs(node[p].right);
    ans[tot]=node[p].date;
    tot++;
}

int main()
{
    while(~scanf("%d",&n))
    {
        int i;
        tot=1;
        for(i=0; i<=n; i++)
        {
            node[i].left=-1;
            node[i].right=-1;
            node[i].date=-1;
        }

        p1=p2=1;
        for(int i=1;i<=2*n;i++)
        {
            char op[10]; scanf("%s",op);
            if(op[1]=='u')
            {
                int num; scanf("%d",&num);
                s.push(num);
                Preorder[p1++]=num;
            }
            else if(op[1]=='o')
            {
                int top=s.top(); s.pop();
                Inorder[p2++]=top;
            }
        }

        for(i=1; i<=n; i++)  APreorder[Preorder[i]]=i;
        for(i=1; i<=n; i++ )AInorder[Inorder[i]]=i;
        
        Build_Binary_Tree(1,n,0);
       
        tot=0;
        dfs(1);
        for(i=0; i<n; i++)
        {
            if(i<n-1) printf("%d ",ans[i]);
            else printf("%d\n",ans[i]);
        }
    }
    return 0;
}

 

posted @ 2016-07-03 10:41  Fighting_Heart  阅读(301)  评论(0编辑  收藏  举报