1086 Tree Traversals Again (25 分)给定两个遍历序列,求另一个序列(套模板)

这道题很顺利,和上一题很像,孰能生巧!加油!!上提做的很崩溃,这道题就好了特别多!!!

#include<iostream>
#include<stack>
#include<cstring>
using namespace std;
const int maxn=31;
int n;
int pre[maxn],in[maxn];
struct node{
    
    
    int data;
    node *left,*right;
};
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->left=create(preL+1,preL+numleft,inL,k-1);
    root->right=create(preL+numleft+1,preR,k+1,inR);
    return root;
}
int  num=0;
void postorder(node* root){
    
    
    if(root==NULL)
        return;
    postorder(root->left);
    postorder(root->right);
    printf("%d",root->data);
    num++;
    if(num<n)
        printf(" ");
}
int main()
{
    
    
    char str[5];
    int num1=0,num2=0;
    stack<int> s;
    cin>>n;
    for(int i=0;i<2*n;i++){
    
    
        cin>>str;
        if(!strcmp(str,"Push"))
        {
    
    
            int temp;
            cin>>temp;
            s.push(temp);
            pre[num1++]=temp;
        }
        else{
    
    
            in[num2++]=s.top();
            s.pop();
        }
    }
    node* root=create(0,n-1,0,n-1);
    postorder(root);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42835526/article/details/113666716