大家好,我是 ztrztr,今天我们来讲完全二叉树的遍历。
完全二叉树
完全二叉树,像字面上的意思,是有 2 n 2^n 2n (加上根节点)个节点。我们先讲一讲如何储存完全二叉树。
我们用一个数组来储存,我们定义如果 A i A_i Ai 为子节点, A i ∗ 2 A_{i*2} Ai∗2 为母节点(左边的), A i ∗ 2 + 1 A_{i*2+1} Ai∗2+1 为父节点(右边的)。
完全二叉树遍历
非回溯
如果是非回溯遍历就好办了,我们用递归函数实现就行了:
#include <bits/stdc++.h>
using namespace std;
int a[10000005];
void pre(int nw) {
cout << a[nw] << " ";
if (a[nw * 2]) pre(nw * 2);
if (a[nw * 2 + 1]) pre(nw * 2 + 1);
}
void mid(int nw) {
if (a[nw * 2]) mid(nw * 2);
cout << a[nw] << " ";
if (a[nw * 2 + 1]) mid(nw * 2 + 1);
}
void post(int nw) {
if (a[nw * 2]) post(nw * 2);
if (a[nw * 2 + 1])post(nw * 2 + 1);
cout << a[nw] << " ";
}
int findN(int N)
{
int sum = 1;
while (true)
{
if (sum * 2 > N)
{
return sum * 2;
}
sum = sum * 2;
}
}
int main() {
ios::sync_with_stdio(false);
cout.tie();
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
a[i] = i;
}
pre(1);
cout << "\n";
mid(1);
cout << "\n";
post(1);
return 0;
}
回溯
如果回溯的话,我们需要调整,每次到底回到上一个时输出一下,就行了,我就只展示前序遍历,其他一样:
#include <bits/stdc++.h>
using namespace std;
long long a[10000005], book[10000005];
void dfs(int i) {
cout << i << "->";
if(a[2 * i]) {
dfs(i * 2);
cout << i << "->";
}
if(a[2 * i + 1]) {
dfs(2 * i + 1);
if(i != 1) {
cout << i << "->";
}
else {
cout << i;
}
}
return;
}
int main() {
ios::sync_with_stdio(false);
cout.tie();
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
a[i] = i;
}
dfs(1);
return 0;
}
谢谢大家,我的文章到这了,大家不要忘记点赞呀!!
联系方式:ztrztr–luogu