L2-035 完全二叉树的层序遍历
前提必须是完全二叉树,才能有这种转化方式。
后序到层次,
#include <bits/stdc++.h>
using namespace std;
int n,post[40],cx[40],cnt=1;
void dfs(int index) {//index是层数数组的下标
if (index > n) return;
dfs(2 * index);
dfs(2 * index + 1);
cx[index] = post[cnt];
cnt++;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> post[i];
}
dfs(1);
for (int i = 1; i <= n; i++) {
cout << cx[i];
if (i < n) cout << " ";
}
return 0;
}
同样,先序转换到层次,
#include <bits/stdc++.h>
using namespace std;
int n,post[40],cx[40],cnt=1;
void dfs(int index) {//index是层数数组的下标
if (index > n) return;
cx[index] = post[cnt];
cnt++;
dfs(2 * index);
dfs(2 * index + 1);
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> post[i];
}
dfs(1);
for (int i = 1; i <= n; i++) {
cout << cx[i];
if (i < n) cout << " ";
}
return 0;
}
中序转换到层次,
#include <bits/stdc++.h>
using namespace std;
int n,post[40],cx[40],cnt=1;
void dfs(int index) {//index是层数数组的下标
if (index > n) return;
dfs(2 * index);
cx[index] = post[cnt];
cnt++;
dfs(2 * index + 1);
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> post[i];
}
dfs(1);
for (int i = 1; i <= n; i++) {
cout << cx[i];
if (i < n) cout << " ";
}
return 0;
}