描述
Given an array A1, A2, … AN, your task is to build a binary treee T which satisfies the following requirments:
T is a min-heap;
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的中序遍历的序列 A1⋯An 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;
}