思路
先排序(冒泡排序)
用数组建一棵空树(用数组,填好左右儿子)
中序遍历填数( Tree::travIn() )
顺序输出即为层次遍历( Tree::travLevel() )
code
# include <iostream>
# include <cstdio>
# include <cstring>
int A[1010];
struct Node {
int data, left, right;
};
struct Tree {
int n;
Node * treeList;
int root;
Tree(int _n) :n(_n), root(1)
{
treeList = new Node[1010];
for (int i = 1; i <= n; ++i)
{
treeList[i].left = (i * 2 <= n) ? i * 2 : -1;
treeList[i].right = (i * 2 + 1 <= n) ? i * 2 + 1 : -1;
}
}
void travIn(int rt, int & order)
{
if (rt == -1) return;
travIn(treeList[rt].left, order);
treeList[rt].data = A[order++];
travIn(treeList[rt].right, order);
}
void travLevel(void)
{
for (int i = 1; i <= n; ++i)
printf("%d%s", treeList[i].data, i == n ? "\n" : " ");
}
};
void bubbleSort(int n) //A从0
{
for (int i = n - 1; i > 0; --i)
for (int j = 0; j < i; ++j)
if (A[j] > A[j + 1])
{
int t = A[j];
A[j] = A[j + 1];
A[j + 1] = t;
}
}
int main(void)
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d", &A[i]);
bubbleSort(n);
Tree t(n);
int order = 0;
t.travIn(t.root, order);
t.travLevel();
return 0;
}