7-5 Tree Traversals Again (25分)

 

 

 

 解题思路:入栈顺序即为前序,出栈顺序为中序,等价于求由前序和中序确定后序

#include <stdio.h>
#include <string.h>
#include <malloc.h>
typedef char Element[5];
typedef struct TNode {
    int data;
    struct TNode *left,*right;
}*Tree;
Tree PostOrder(int pre[],int low,int high,int in[],int left,int right) {
    Tree T=malloc(sizeof(struct TNode));
    T->data=pre[low];
    
    int i,pos;
    for(i=left; i<=right; i++) {
        if(pre[low]==in[i]) {
            pos=i;
            break;
        }
    }
    int llen=pos-left,rlen=right-pos;

    if(llen)
        T->left=PostOrder(pre,low+1,low+llen,in,left,pos-1);
    else
        T->left=NULL;
    if(rlen)
        T->right=PostOrder(pre,low+llen+1,high,in,pos+1,right);
    else
        T->right=NULL;
    return T;
}

int t=0;
void PostTrav(Tree T,int post[]) {
    if(T) {
        PostTrav(T->left,post);
        PostTrav(T->right,post);
        post[t++]=T->data;
    }
}
int main() {
    int n,i,j=0,k=0;
    scanf("%d",&n);
    int a[n],b[n],c[n];
    int stack[n];
    int top=-1;
    Element str;
    Tree T=NULL;
    for(i=0; i<2*n; i++) {
        scanf("%s",str);
        if(!strcmp(str,"Push")) {

            scanf("%d",&a[j]);
            stack[++top]=a[j];
            j++;
        } else {
            b[k++]=stack[top--];
        }
    }
    T=PostOrder(a,0,n-1,b,0,n-1);
    PostTrav(T,c);
    for(i=0;i<n;i++)
    {
        if(i)
        printf(" ");
        printf("%d",c[i]);
    }
    return 0;
}

 

posted @ 2020-04-23 19:54  跃鱼  阅读(196)  评论(0编辑  收藏  举报