题面
题解
完全二叉树采用顺序存储方式,如果有左孩子,则编号为2i,如果有右孩子,编号为2i+1,然后按照后序遍历的方式(左右根),进行输入,最后顺序输出即可。
代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 35;
int n;
int tree[N];
int postorder[N];
int idx = 0;
//后序遍历(左右根)
void dfs(int root) {
if (root > n) return;
dfs(root * 2);
dfs(root * 2 + 1);
tree[root] = postorder[idx++];
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> postorder[i];
dfs(1);
cout << tree[1];
for (int i = 2; i <= n; i++) {
cout << " " << tree[i];
}
cout<<endl;
return 0;
}