小根堆的性质+ 中序可以建树。
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
node *lc, *rc;
};
vector<int> in, ans;
node *tree (int inL, int inR) {
if (inL > inR) return NULL;
node *root = new node();
int k = inL, minNum = in[inL], pos;
while (k <= inR) {
if (minNum >= in[k]) {
minNum = in[k];
pos = k;
}
k++;
}
root->data = in[pos];
// cout << in[pos] << endl;
root->lc = tree (inL, pos - 1);
root->rc = tree (pos + 1, inR);
return root;
}
int main() {
int n;
scanf ("%d", &n);
in.resize(n);
for (int i = 0; i < n; i++) {
scanf ("%d", &in[i]);
}
node *root = tree (0, n - 1);
queue<node*> q;
q.push(root);
while (!q.empty()) {
node *now = q.front();
q.pop();
ans.push_back(now->data);
if (now->lc != NULL) q.push(now->lc);
if (now->rc != NULL) q.push(now->rc);
}
for (int i = 0; i < ans.size(); i++) {
if (i != 0) printf (" ");
printf ("%d", ans[i]);
}
}