其他分享
首页 > 其他分享> > PAT-A刷题::1020 Tree Traversals

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();
}

 

标签:Node,PAT,cur,int,Traversals,Tree,pos,qnode,root
来源: https://blog.csdn.net/qq_41228018/article/details/104844698