分析
给出小顶堆的中序,输出层序
因此只需要每次找出序列中最小的,即为父结点
代码
#include<bits/stdc++.h>
using namespace std;
struct Tree {
int key;
Tree* lchild,* rchild;
Tree(int x) {
key = x;
lchild = rchild = NULL;
}
};
int quantity;
vector<int>heap_ordered;
Tree* BuildTree(Tree*, int, int);
void LevelPrint(Tree*);
int main() {
scanf("%d", &quantity);
heap_ordered.resize(quantity);
for (int i = 0; i < quantity; i++)
scanf("%d", &heap_ordered[i]);
Tree* root{ NULL };
root = BuildTree(root, 0, quantity - 1);
LevelPrint(root);
return 0;
}
Tree* BuildTree(Tree* T,int left,int right) {
if (right - left < 0)
return T;
auto x = min_element(heap_ordered.begin() + left, heap_ordered.begin() + right + 1) - heap_ordered.begin();
T = new Tree(heap_ordered[x]);
T->rchild = BuildTree(T->rchild, x + 1, right);
T->lchild = BuildTree(T->lchild, left, x - 1);
return T;
}
void LevelPrint(Tree* T) {
queue<Tree*>temp;
temp.push(T);
bool flag{ true };
while (1) {
flag ? printf("%d", T->key), flag = false : printf(" %d", T->key);
if (T->lchild != NULL)
temp.push(T->lchild);
if (T->rchild != NULL)
temp.push(T->rchild);
temp.pop();
if (!temp.empty())
T = temp.front();
else
break;
}
}