先序中序后序
2025-02-03 09:42:40
发布于:上海
#include<bits/stdc++.h>
using namespace std;
int left1[110],right1[110];
int n;
//先序 自私 中左右
void dfs(int u){
cout<<u<<" ";
if(left1[u]!=0)dfs(left1[u]);
if(right1[u]!=0)dfs(right1[u]);
}
//中序 偏爱左孩子 左中右
void dfs_1(int u){
if(left1[u]!=0)dfs_1(left1[u]);
cout<<u<<" ";
if(right1[u]!=0)dfs_1(right1[u]);
}
//后序 左右中
void dfs_2(int u){
if(left1[u]!=0)dfs_2(left1[u]);
if(right1[u]!=0)dfs_2(right1[u]);
cout<<u<<" ";
}
int main(){
cin>>n;
for(int i=1;i<=n;i++){
int tr,l,r;
cin>>tr>>l>>r;
if(l!=0)left1[tr] = l;
if(r!=0)right1[tr] = r;
}
dfs(1);
cout<<endl;
dfs_1(1);
cout<<endl;
dfs_2(1);
return 0;
}
这里空空如也
有帮助,赞一个