浙江大学PAT甲级A1043(C++)题解

#include <iostream>
#include <vector>
using namespace std;
struct node{
     
    int data;
    node* lchild;
    node* rchild;
};

void insert(node* &root,int data){
     
    if(root==NULL){
     
        root = new node;
        root->data = data;
        root->lchild=root->rchild =NULL;
        return;
    }
    if(data<root->data){
     
        insert(root->lchild,data);
    }else{
     
        insert(root->rchild,data);
    }
}
void preOrder(node* root,vector<int> &vi){
     
    if(root==NULL){
     
        return;
    }
    vi.push_back(root->data);
    preOrder(root->lchild,vi);
    preOrder(root->rchild,vi);
}
void mirrorPreOrder(node* root,vector<int> &vi){
     
    if(root==NULL){
     
        return;
    }
    vi.push_back(root->data);
    mirrorPreOrder(root->rchild,vi);
    mirrorPreOrder(root->lchild,vi);
}
void postOrder(node* root,vector<int> &vi){
     
    if(root==NULL){
     
        return;
    }
    postOrder(root->lchild,vi);
    postOrder(root->rchild,vi);
    vi.push_back(root->data);
}
void mirrorPostOrder(node* root,vector<int> &vi){
     
    if(root==NULL){
     
        return;
    }
    mirrorPostOrder(root->rchild,vi);
    mirrorPostOrder(root->lchild,vi);
    vi.push_back(root->data);
}
int main() {
     
    int N;
    cin>>N;

    node * root = NULL;
    vector<int> v;
    for(int i=0;i<N;i++){
     
        int data;
        cin>>data;
        v.push_back(data);
        insert(root,data);
    }
    vector<int> post,pre,Mpost,Mpre;
    preOrder(root,pre);
    postOrder(root,post);
    mirrorPreOrder(root,Mpre);
    mirrorPostOrder(root,Mpost);
    if(v==pre){
     
        cout<<"YES\n";
        for(int i =0;i<post.size();i++){
     
            if(i==0){
     
                cout<<post[i];
            } else{
     
                cout<<" "<<post[i];
            }
        }
    } else if (v==Mpre){
     
        cout<<"YES\n";
        for(int i =0;i<Mpost.size();i++){
     
            if(i==0){
     
                cout<<Mpost[i];
            } else{
     
                cout<<" "<<Mpost[i];
            }
        }
    } else{
     
        cout<<"NO\n";
    }
    return 0;
}

你可能感兴趣的:(浙大PAT甲级,C++题解)