每日一题之 hiho205 Building Heap

根据给定的数组构建一个满足最小堆性质的二叉树,并保证中序遍历序列与原数组相同。题目提供了样例输入和输出,通过找到最小值作为根节点并递归构建左右子树,可以还原出二叉树并输出其先序遍历序列。

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

描述
Given an array A1, A2, … AN, your task is to build a binary treee T which satisfies the following requirments:

  1. T is a min-heap;

  2. The inorder traversal sequence of T is A1, A2, … AN.

For example if the array is 3, 2, 8, 1, 4, 7, the tree is as below:

      1
     / \
    2   4
   / \   \
  3   8   7

输入
The first line contain an integer N denoting the array length. (1 <= N <= 100)

The second line contains N distinct integers denoting A1, A2, … AN. (1 <= Ai <= 1000000)

输出
Output the preorder traversal sequence of T.

样例输入
6
3 2 8 1 4 7
样例输出
1 2 3 8 4 7

题意:

题目意思是有这样一个棵二叉树 T,满足 T 是小根堆,并且给出T的中序遍历的序列 A1An A 1 ⋯ A n 让你输出这个二叉树的T的先序遍历的序列。

思路:

结合中序遍历的性质和小根堆的性质,容易得到,每次找到序列中最小值作为根,且这个值将序列划分成两块,该值左边的就是其左子树,右边的就是其右子树。依照这个思想重建二叉树,然后打印。

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;


const int INF = 1e9+5;

int A[105];

typedef struct node
{
    int val;
    struct node *left,*right;
}ndoe,*BiTree;


BiTree build(int A[],int st,int ed)
{
    BiTree root = nullptr;

    int minval = INF,idx = -1;
    for (int i = st; i < ed; ++i) {
        if (A[i] < minval) {
            minval = A[i];
            idx = i;
        }
    }
    if (minval != INF && idx != -1) {
        root = new node();
        root->val = minval;
        root->left = build(A,st,idx);
        root->right = build(A,idx+1,ed);
    } 
    return root;
}

void visit(node *x)
{

    cout<<x->val<<' ';
}

void preOrder(BiTree T)
{
    if(T != nullptr){
        visit(T);
        preOrder(T->left);
        preOrder(T->right);
    }

}

int main()
{
    int n;
    cin >> n;
    for (int i = 0; i < n; ++i)
        cin >> A[i];

    BiTree root = build(A,0,n);

    preOrder(root);
    cout << endl;
    return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值