- 周嘉濠 的博客
二叉数
- @ 2025-3-1 16:11:08
二叉树遍历
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+10;
struct node{
int data;
int l;
int r;
}Node[maxn];
void L(int root){
queue<int> q;
q.push(root);
while(!q.empty()){
int now = q.front();
q.pop();
cout << Node[now].data << " ";
if(Node[now].l!=-1){
q.push(Node[now].l);
}
if(Node[now].r!=-1){
q.push(Node[now].r);
}
}
}
void p(int root){
if(root == -1){
return ;
}
cout << Node[root].data << " ";
p(Node[root].l);
p(Node[root].r);
}
void i(int root){
if(root == -1){
return ;
}
i(Node[root].l);
cout << Node[root].data << " ";
i(Node[root].r);
}
void a(int root){
if(root == -1){
return ;
}
a(Node[root].l);
a(Node[root].r);
cout << Node[root].data << " ";
}
int main(){
int n;
cin >> n;
for(int i = 1;i <= n;i++){
cin >> Node[i].l >> Node[i].r;
Node[i].data=i;
}
p(1);
cout << '\n';
i(1);
cout << '\n';
a(1);
cout << '\n';
L(1);
return 0;
}