树
2025-12-14 18:36:26
发布于:广东
前序遍历:
#include <bits/stdc++.h>
using namespace std;
int n;
int a[100010];
void f(int x) {
cout << a[x] << " ";
if (2 * x <= n) {
f(2 * x);
}
if (2 * x + 1 <= n) {
f(2 * x + 1);
}
}
int main () {
cin >> n;
for (int i = 1;i <= n;i++) {
cin >> a[i];
}
f(1);
return 0;
}
中序遍历:
#include <bits/stdc++.h>
using namespace std;
int n;
int a[100010];
void f(int x) {
if (2 * x <= n) {
f(2 * x);
}
cout << a[x] << " ";
if (2 * x + 1 <= n) {
f(2 * x + 1);
}
}
int main () {
cin >> n;
for (int i = 1;i <= n;i++) {
cin >> a[i];
}
f(1);
return 0;
}
后序遍历:
#include <bits/stdc++.h>
using namespace std;
int n;
int a[100010];
void f(int x) {
if (2 * x <= n) {
f(2 * x);
}
if (2 * x + 1 <= n) {
f(2 * x + 1);
}
cout << a[x] << " ";
}
int main () {
cin >> n;
for (int i = 1;i <= n;i++) {
cin >> a[i];
}
f(1);
return 0;
}
这里空空如也
















有帮助,赞一个