二叉树的生成与层序遍历-PAT A1020

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hbhgyu/article/details/82224420
题目要求是:给出一棵二叉树的后序遍历序列和中序遍历序列,求这棵二叉树的层序遍历序列。
#include <cstdio>
#include <queue>
using namespace std;

const int maxn = 35;
int post[maxn] = {0};
int in[maxn] = {0};
int traversal[maxn] = {0};
int N;

struct node{
    int data;
    node *lchild;
    node *rchild;
};

//当前后序序列区间为[postL, postR],中序序列区间为[inL, inR],函数返回二叉树的根节点
node *create(int postL, int postR, int inL, int inR)
{
    if(postL > postR)
        return NULL;
    node *root = new node;
    root->data = post[postR];   //新结点的数据域为根结点的值
    int k;
    for(k = inL; k <= inR; k++){
        if(in[k] == post[postR])
            break;
    }
    int numLeft = k - inL;  //左子树的结点数目
    root->lchild = create(postL, postL+numLeft-1, inL, k-1);
    root->rchild = create(postL+numLeft, postR-1, k+1, inR);
    return root;
}

void bfs(node *root)
{
    queue<node *> q;
    q.push(root);
    int k = 1;
    while(!q.empty()){
        node *top = q.front();
        q.pop();
        traversal[k++] = top->data;
        if(top->lchild != NULL)
            q.push(top->lchild);
        if(top->rchild != NULL)
            q.push(top->rchild);
    }
}

int main()
{
    scanf("%d", &N);
    for(int i = 1; i <= N; i++)
        scanf("%d", &post[i]);
    for(int i = 1; i <= N; i++)
        scanf("%d", &in[i]);
    node *root = create(1, N, 1, N);
    bfs(root);
    for(int i = 1; i <= N; i++){
        if(i != N)
            printf("%d ", traversal[i]);
        else
            printf("%d\n", traversal[i]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hbhgyu/article/details/82224420