1119 Pre- and Post-order Traversals

Posted feiief

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}

 

以上是关于1119 Pre- and Post-order Traversals的主要内容,如果未能解决你的问题,请参考以下文章

1119 Pre- and Post-order Traversals (30 分)

PAT 1119 Pre- and Post-order Traversals

1119 Pre- and Post-order Traversals

[二叉树建树]1119. Pre- and Post-order Traversals (30) (前序和后序遍历建立二叉树)

1119 Pre- and Post-order Traversals (30 分)难度: 难 / 知识点: 树的构建

A1119 Pre- and Post-order Traversals (30分)