树_A1086 Tree Traversals Again (25 分)

核能气质少年 提交于 2019-11-28 00:26:39

 

/*
先序序列区间[preL,preR]
中序序列区间[inL,inR]
左子树的结点个数numLeft=k-inL
左子树的先序[preL+1,preL+numLeft]
左子树的中序[inL,k-1]
右子树的先序[preL+numLeft+1,preR]
右子树的中序[k+1,inR]
*/

#include<cstdio>
#include<cstring>
#include<stack>
#include<algorithm>
using namespace std;
const int maxn=50;
struct node{
    int data;
    node* lchild;
    node* rchild;
};

int pre[maxn],in[maxn],post[maxn];
int n;//结点个数

node* create(int preL,int preR,int inL,int inR){
    if(preL>preR){
        return NULL;
    }
    node* root=new node;
    root->data=pre[preL];//新结点的数据域为根结点的值
    int k;
    for(k=inL;k<=inR;k++){
        if(in[k]==pre[preL]){
            break;
        }
    } 
    int numLeft=k-inL;//左子树的结点个数
    root->lchild=create(preL+1,preL+numLeft,inL,k-1);
    root->rchild=create(preL+numLeft+1,preR,k+1,inR);
    return root; 
} 

int num=0;//已输出的结点个数
void postorder(node* root){
    if(root==NULL){
        return ;
    }
    postorder(root->lchild);
    postorder(root->rchild);
    printf("%d",root->data);
    num++;
    if(num<n) printf(" ");
} 

int main(){
    scanf("%d",&n);
    char str[5];
    stack<int> st;
    int x,preIndex=0,inIndex=0;
    for(int i=0;i<2*n;i++){
        scanf("%s",str);
        if(strcmp(str,"Push")==0) {
            scanf("%d",&x);
            pre[preIndex++]=x;
            st.push(x);
        }else{
            in[inIndex++]=st.top();
            st.pop();
        }
    }
    node* root=create(0,n-1,0,n-1);
    postorder(root);
    return 0;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!