c++代码
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 40;
int n;
int tree[N];//存放二叉树
//由于是完全二叉树,只要结点数确定,二叉树的形状也就确定了
//而且用数组存完全二叉树时,若已知一个结点存储在数组的下标x,则该结点的左孩子下标为2*x,右孩子下标为x*2+1
//根据二叉树的后序遍历递归构建二叉树
void build(int x) {
if (x > n) return;
//构建左子树
build(x * 2);
//构建右子树
build(x * 2 + 1);
cin >> tree[x];
}
//build函数类似二叉树后序遍历的递归写法
int main() {
cin >> n;
build(1);
//完全二叉树在数组中的存放顺序就是层次遍历
for (int i = 1; i < n; i++) cout << tree[i] << " ";
cout << tree[n];
return 0;
}