zoukankan      html  css  js  c++  java
  • 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
    ");
        }else{
            printf("Yes
    ");
        }
        for(int i=0;i<N;i++){
            if(i!=0) printf(" ");
            printf("%d", inorder[i]);
        }
        printf("
    ");
        return 0;
    }
  • 相关阅读:
    [hdu4436 str2int]后缀自动机SAM(或后缀数组SA)
    bytedance专题
    LSTM+CRF维特比解码过程
    spark core类梳理
    spark源码阅读---Utils.getCallSite
    python2.7官方文档阅读笔记
    cs224d---词向量表示
    cs231n---强化学习
    cs231n---生成模型
    Spring 2017 Assignments3
  • 原文地址:https://www.cnblogs.com/FEIIEF/p/12474835.html
Copyright © 2011-2022 走看看