1119 Pre- and Post-order Traversals

link

 

 

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <cstring>
#include <set>
#include <unordered_map>
#include <cmath>
# define LL long long
using namespace std;


int N;
int pre[30];
int post[30];
int notunique;
unordered_map<int,int> posinpost;
struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int v):val{v},left{NULL}, right{NULL} {}
};

TreeNode* buildTree(int preleft, int preright, int postleft, int postright){
    TreeNode* root=new TreeNode(pre[preleft]);

    if(preleft==preright) return root;

    int next=pre[preleft+1];
    int pos=posinpost[next];
    int leftnums=pos-postleft+1;
    if(pos==postright-1){
        notunique=1;
        root->left=buildTree(preleft+1,preleft+1+leftnums-1,postleft,pos);
        return root;
    }
    root->left=buildTree(preleft+1,preleft+1+leftnums-1,postleft,pos);
    root->right=buildTree(preleft+1+leftnums,preright,pos+1,postright-1);
    return root;
}

void in(TreeNode* root, vector<int>& inorder){
    if(root==NULL) return ;
    in(root->left,inorder);
    inorder.push_back(root->val);
    in(root->right,inorder);
}

int main(){
    cin>>N;
    for(int i=0;i<N;i++){
        scanf("%d", pre+i);
    }
    for(int i=0;i<N;i++){
        scanf("%d", post+i);
        posinpost[post[i]]=i;
    }
    TreeNode* root=buildTree(0,N-1,0,N-1);
    vector<int> inorder;
    in(root,inorder);
    if(notunique==1){
        printf("No\n");
    }else{
        printf("Yes\n");
    }
    for(int i=0;i<N;i++){
        if(i!=0) printf(" ");
        printf("%d", inorder[i]);
    }
    printf("\n");
    return 0;
}

 

posted @ 2020-03-12 18:15  feibilun  阅读(122)  评论(0编辑  收藏  举报