二叉树三种遍历方式模版
2024-08-06 10:31:59
发布于:上海
前序遍历
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int a[N];
int n;
//输出以root为根的二叉树先序遍历
void dfs(int root){
if(root>n) return ;
cout<<a[root]<<' ';
dfs(root2);
dfs(root2+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 a[N];
int n;
//输出以root为根的二叉树先序遍历
void dfs(int root){
if(root>n) return ;
dfs(root*2);
cout<<a[root]<<' ';
dfs(root*2+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 a[N];
int n;
void postorder(int root){
if(root>n) return ;
postorder(root2);
postorder(root2+1);
cout<<a[root]<<' ';
}
int main(){
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
postorder(1);
return 0;
}
这里空空如也
有帮助,赞一个