PAT-A刷题::1020 Tree Traversals

shift+enter:vscode快速输入

#include<cstdio>
#include<queue>
#define I 31

using namespace std;
int n;
int pre[I], in[I], post[I];

struct Node{
    int data;
    Node *left = NULL, *right = NULL;
};

Node* create(int postL,int postR,int inL,int inR)
{
    if(postL>postR)
        return NULL;
    
    Node *root = new Node;
    root->data = post[postR];

    int pos;
    for (pos = inL; pos < inR; pos++)
        if(in[pos]==post[postR])
            break;
    int leftcnt = pos - inL;

    root->left = create(postL, postL + leftcnt - 1, inL, pos - 1);
    root->right = create(postL + leftcnt, postR - 1, pos + 1, inR);
    return root;
}

void BFS(Node *node)
{
    queue<Node *> qnode;
    Node *cur;
    int cnt = 0;

    qnode.push(node);

    while(!qnode.empty())
    {
        cur = qnode.front();
        qnode.pop();
        cnt++;
        printf("%d", cur->data);
        if(cnt<n)
            printf(" ");
        if(cur->left!=NULL)
            qnode.push(cur->left);
        if(cur->right!=NULL)
            qnode.push(cur->right);
    }
}

int main()
{
    scanf("%d", &n);
    for (int i = 0; i < n;i++)
        scanf("%d", &post[i]);
    for (int i = 0; i < n;i++)
        scanf("%d", &in[i]);

    Node *root = create(0, n - 1, 0, n - 1);

    BFS(root);

    getchar();
}

 

上一篇:cmake与qmake


下一篇:【原创】关于IIS6.0环境下w3wp.exe进程消失的问题