L2-035 完全二叉树的层序遍历
题目描述:
一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是完美二叉树。对于深度为 D 的,有 N 个结点的二叉树,若其结点对应于相同深度完美二叉树的层序遍历的前 N 个结点,这样的树就是完全二叉树。
给定一棵完全二叉树的后序遍历,请你给出这棵树的层序遍历结果。
输入格式:
输入在第一行中给出正整数 N(≤30),即树中结点个数。第二行给出后序遍历序列,为 N 个不超过 100 的正整数。同一行中所有数字都以空格分隔。
输出格式:
在一行中输出该树的层序遍历序列。所有数字都以 1 个空格分隔,行首尾不得有多余空格。
输入样例:
8
91 71 2 34 10 15 55 18
输出样例:
18 34 55 71 2 10 15 91
分析:
在In中保存输入的后序遍历序列,在dfs保存从根节点开始按层序遍历序列的序号。深度优先搜索,index标表示当前节点,大于n则返回。按照完全二叉树的遍历原理进行后序遍历,先进入左右子树(编号为index*2 和 index*2+1,即index右移1位,和index右移1位+1),cnt为后序遍历的位置标记,并将当前所在的后序遍历的元素,填入dfs[index]内。
代码:
#include <bits/stdc++.h>
using namespace std;
int n, cnt, In[32], dfs[32];
void Func(int index) {
if (index > n) return;
Func(index << 1);
Func(index << 1 | 1);
dfs[index] = In[cnt++];
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> In[i];
Func(1);
cout << dfs[1];
for (int i = 2; i <= n; i++) cout << ' ' << dfs[i];
return 0;
}
引申:
1.根据先序遍历,输出层次遍历
#include <bits/stdc++.h>
using namespace std;
int n, cnt, In[32], dfs[32];
void Func(int index) {
if (index > n) return;
dfs[index] = In[cnt++];
Func(index << 1);
Func(index << 1 | 1);
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> In[i];
Func(1);
cout << dfs[1];
for (int i = 2; i <= n; i++) cout << ' ' << dfs[i];
return 0;
}
2.根据中序遍历,输出层次遍历
#include <bits/stdc++.h>
using namespace std;
int n, cnt, In[32], dfs[32];
void Func(int index) {
if (index > n) return;
Func(index << 1);
dfs[index] = In[cnt++];
Func(index << 1 | 1);
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> In[i];
Func(1);
cout << dfs[1];
for (int i = 2; i <= n; i++) cout << ' ' << dfs[i];
return 0;
}
3.根据后序遍历,输出层次遍历
#include <bits/stdc++.h>
using namespace std;
int n, cnt, In[32], dfs[32];
void Func(int index) {
if (index > n) return;
Func(index << 1);
Func(index << 1 | 1);
dfs[index] = In[cnt++];
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> In[i];
Func(1);
cout << dfs[1];
for (int i = 2; i <= n; i++) cout << ' ' << dfs[i];
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人