PAT A1020 Tree Traversals (25 分)

题意

给定一棵二叉树的后序序列和中序序列,输出它的层序序列

注意点

题解

思路:
①读取数据
②根据后序序列和中序序列重建二叉树
③层序遍历二叉树,输出每个结点的值
函数:
①重建二叉树函数create
和算法笔记先序和中序构建的函数类似,注意numLeft的取值
②层序遍历函数layerOrder
queue中的元素应该是指针类型

#include <stdio.h>
#include <queue>
using namespace std;
const int maxn = 35;
//新建结点
struct node {
    int data;
    node* lchild;
    node* rchild;
};
int n, post[maxn], in[maxn];
//根据后序序列和中序序列重建二叉树
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;
    //左子树中序区间为[inL, k-1],左子树后序区间为[postL, postL+numLeft-1]
    root->lchild = create(postL, postL+numLeft-1, inL, k-1);
    //右子树中序区间为[k+1, inR],右子树后序区间为[postL+numLeft, postR-1]
    root->rchild = create(postL+numLeft, postR-1, k+1, inR);
    return root;
}
//层序遍历
void layerOrder(node* root) {
    queue<node*> q;
    q.push(root);
    while (!q.empty()) {
        node* now = q.front();
        q.pop();
        //访问结点
        if (now != root) printf(" ");
        printf("%d", now->data);
        //左右孩子入队
        if (now->lchild != NULL) q.push(now->lchild);
        if (now->rchild != NULL) q.push(now->rchild);
    }
}
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);
    //层序遍历二叉树
    layerOrder(root);
    printf("\n");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值