【计算机考研408】(二叉树+堆)(中序遍历+层序遍历)非常适合408算法题考察一道PAT甲级题目 1167 Cartesian Tree

题意

给你一个最小堆的中序遍历,要求你输出他的层序遍历

题解

  1. 构建二叉树
  2. 层序遍历
#include <bits/stdc++.h>
using namespace std;

typedef struct BitNode{
    int data;
    struct BitNode *lchild, *rchild;
}BitNode, *BitTree;
int v[35];

void create(BitTree &p, int L, int R){
    if (L > R) return;
    int minidx = L;
    for(int i = L; i <= R; i++){
        if (v[i] < v[minidx]){
            minidx = i;
        }
    }
    p = (BitTree)malloc(sizeof(BitNode));
    p->data = v[minidx];
    //cout << v[minidx] << '\n';
    create(p->lchild, L, minidx - 1);
    create(p->rchild, minidx + 1, R);
}

int main(){
    int n; cin >> n;
    //输入的是中序遍历最小堆的情况
    for(int i = 0; i < n; i++){
        cin >> v[i];
    }
    BitTree ans;
    create(ans, 0, n-1);
    
    //层序遍历
    queue<BitTree> q;
    q.push(ans);
    bool firstprint = true;
    while(!q.empty()){
        BitTree temp = q.front();
        if (firstprint){
            cout << temp->data;
            firstprint = false;
        }
        else {
            cout << " " << temp->data;
        }
        if(temp->lchild != NULL)
            q.push(temp->lchild);
        if (temp->rchild != NULL)
            q.push(temp->rchild);
        
        q.pop();
        
    }
    cout << '\n';
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值