1020. Tree Traversals (25)

来源:互联网 发布:淘宝刷销量平台可靠吗 编辑:程序博客网 时间:2024/06/01 08:40

1020. Tree Traversals (25)

#include <iostream>#include <stdio.h>#include <vector>#include <cmath>#include <stack>#include <queue>#include <deque>#include <algorithm>#include <map>using namespace std;struct TreeNode {    int val;    struct TreeNode *left;    struct TreeNode *right;    TreeNode(int x) :    val(x), left(NULL), right(NULL) {    }};TreeNode *create(vector<int> pre,vector<int> in,int first,int last,int &curRoot){    if (first>last){        curRoot++;        return NULL;    }    TreeNode *p = new TreeNode(pre[curRoot]);    auto it = find(in.begin()+first,in.begin()+last+1,pre[curRoot]);    int pos = (int)(it- in.begin());    p->right =create(pre, in, pos+1, last, --curRoot);    p->left = create(pre, in, first,pos-1, --curRoot);    return p;}int main(){    int n;    scanf("%d",&n);    vector<int>post(n),in(n);    for (int i=0; i<n;++i)        scanf("%d",&post[i]);    for (int i=0; i<n;++i)        scanf("%d",&in[i]);    int cur = n-1;    TreeNode * p = create(post, in, 0, (int)in.size()-1, cur);    vector<int>ans;    queue<TreeNode *>q;    if(p)        q.push(p);    while (!q.empty()) {        p = q.front();        q.pop();        ans.push_back(p->val);        if(p->left)            q.push(p->left);        if(p->right)            q.push(p->right);    }    for (int i=0; i<n; ++i)        printf(i==n-1?"%d\n":"%d ",ans[i]);    return 0;}


0 0
原创粉丝点击