1020. Tree Traversals (25)

来源:互联网 发布:递归算法棋子移动java 编辑:程序博客网 时间:2024/06/18 16:17

当年写的感觉太繁琐。
做完甲级1119题之后。
又重新回来写这道题。
AC代码:

#include <bits/stdc++.h>using namespace std;int post[31], in[31];struct node{    int data;    node* left;    node* right;    node(int _data)    {        data = _data;        left = right = NULL;    }};node* build(node* root,int postl,int postr,int inl,int inr){    int i, left, right;    for (i = inl; i <= inr; i++)    {        if (in[i] == post[postr]) break;    }    if (!root) root = new node(in[i]);    if (i != inr)    {        root->right = build(root->right, postl+i-inl, postr-1, i+1, inr);    }    if (i != inl)    {        root->left = build(root->left, postl, postl+i-inl-1, inl, i-1);    }    return root;}int main(void){    int n;    int i;    cin >> n;    for (i = 0; i < n; i++)    {        cin >> post[i];    }    for (i = 0; i < n; i++)    {        cin >> in[i];    }    node* root = NULL;    root = build(root, 0, n-1, 0, n-1);    queue<node*> sup;    sup.push(root);    vector<int> res;    while (!sup.empty())    {        node* front = sup.front();        sup.pop();        res.push_back(front->data);        if (front->left) sup.push(front->left);        if (front->right) sup.push(front->right);    }    for (i = 0; i < n-1; i++)    {        cout << res[i] << " ";    }    cout << res[i];}
原创粉丝点击