【PAT】A1020. Tree Traversals (25)

本文介绍了一个利用后序遍历和中序遍历构建二叉树的方法,并通过广度优先搜索(BFS)对该树进行遍历打印。通过递归方式构造树结构,实现了对树节点的构建与访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A1020. Tree Traversals (25)

#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;

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

treeNode* buildTree(int inl, int inr, int postl, int postr, int* inorder, int* postorder){
    if(postl > postr)
        return NULL;

    treeNode* root = new treeNode;
    root->data = postorder[postr];
    int rootIndex;
    for(int i = inl; i <= inr; i++){
        if(inorder[i] == root->data){
            rootIndex = i;
            break;
        }
    }
    root->lchild = buildTree(inl, rootIndex - 1, postl, postl + rootIndex - inl - 1, inorder, postorder);
    root->rchild = buildTree(rootIndex + 1, inr, postl + rootIndex - inl, postr - 1, inorder, postorder);
    return root;
}

void BFS(treeNode* root, int N){
    queue<treeNode*> q;
    q.push(root);
    int count = 0;
    while (q.size() != 0) {
        treeNode* node = q.front();
        q.pop();
        printf("%d", node->data);
        count++;
        if(count < N)
            printf(" ");
        if(node->lchild)
            q.push(node->lchild);
        if(node->rchild)
            q.push(node->rchild);
    }
}

int main(){
    int N, i;
    scanf("%d", &N);
    int inorder[N], postorder[N];
    for(i = 0; i < N; i++){
        scanf("%d", &postorder[i]);
    }
    for(i = 0; i < N; i++){
        scanf("%d", &inorder[i]);
    }

    treeNode* root = buildTree(0, N - 1, 0, N - 1, inorder, postorder);
    BFS(root, N);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值