二叉树的遍历
2026-11-15 11:52:52
发布于:上海

嗯、对、就是这些了!
三种遍历方式:
1.先序遍历(根左右)
2.中序遍历(左根右)
3.后序遍历(左右根)
前序遍历
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int n,a[N];
void dfs(int x){
cout<<a[x]<<" ";
if(2*x<=n)dfs(2*x);
if(2*x+1<=n)dfs(2*x+1);
}
int main(){
cin>>n;
for(int i=1;i<=n;i++)cin>>a[i];
dfs(1);
return 0;
}
中序遍历
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int n,a[N];
void dfs(int x){
if(2*x<=n)dfs(2*x);
cout<<a[x]<<" ";
if(2*x+1<=n)dfs(2*x+1);
}
int main(){
cin>>n;
for(int i=1;i<=n;i++)cin>>a[i];
dfs(1);
return 0;
}
后序遍历
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int n,a[N];
void dfs(int x){
if(2*x<=n)dfs(2*x);
if(2*x+1<=n)dfs(2*x+1);
cout<<a[x]<<" ";
}
int main(){
cin>>n;
for(int i=1;i<=n;i++)cin>>a[i];
dfs(1);
return 0;
}
这里空空如也

















有帮助,赞一个