题目名字
[题目链接]https://pintia.cn/problem-sets/994805046380707840/problems/1336215880692482058
题意
一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是完美二叉树。对于深度为 D 的,有 N 个结点的二叉树,若其结点对应于相同深度完美二叉树的层序遍历的前 N 个结点,这样的树就是完全二叉树。
给定一棵完全二叉树的后序遍历,请你给出这棵树的层序遍历结果。
思路
如果有左孩子,则编号为2i,如果有右孩子,编号为2i+1,然后按照后序遍历的方式(左右根),进行输入,最后顺序输出即可。
代码
#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;
}