题目描述
有一个 n (n ≤ 个结点的二叉树。给出每个结点的两个子结点编号(均不超过 n),建立一棵二叉树(根节点的编号为 1),如果是叶子结点,则输入
0 0
。
建好树这棵二叉树之后,依次求出它的前序、中序、后序列遍历。
输入格式
第一行一个整数 n,表示结点数。
之后 n 行,第 i 行两个整数 l、r,分别表示结点 i 的左右子结点编号。若 l=0 则表示无左子结点,r=0 同理。
输出格式
输出三行,每行 n 个数字,用空格隔开。
第一行是这个二叉树的前序遍历。
第二行是这个二叉树的中序遍历。
第三行是这个二叉树的后序遍历。
输入输出样例
输入 #1
7 2 7 4 0 0 0 0 3 0 0 0 5 6 0
输出 #1
1 2 4 3 7 6 5
4 3 2 1 6 5 7
3 4 2 5 6 7 1
详细注释版
#include<bits/stdc++.h>
using namespace std;
int n;//节点数
int l[1000005],r[1000005];//结点i的左右子结点编号,范围:10^6
void a(int x){//前序遍历访问到了二叉树的x号点(根左右)
if(x==0) return;//x不存在
cout<<x<<" ";//根
a(l[x]);//左
a(r[x]);//右
}
void b(int x){//中序遍历访问到了二叉树的x号点(左根右)
if(x==0) return;//x不存在
b(l[x]);//左
cout<<x<<" ";//根
b(r[x]);//右
}
void c(int x){//后序遍历访问到了二叉树的x号点(左右根)
if(x==0) return;//x不存在
c(l[x]);//左
c(r[x]);//右
cout<<x<<" ";//根
}
int main() {
//先优化(可有可不有)
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
//输入
cin>>n;
for(int i=1;i<=n;i++){
cin>>l[i]>>r[i];
}
//前序遍历:根左右
a(1);//从根节点1开始前序遍历
cout<<endl;//输出前序遍历
//中序遍历:左根右
b(1);//从根节点1开始中序遍历
cout<<endl;//输出中序遍历
//后序遍历:左右根
c(1);//从根节点1开始后序遍历
cout<<endl;//输出后序遍历
return 0;//完结撒花!
}
无注释版
#include<bits/stdc++.h>
using namespace std;
int n;
int l[1000005],r[1000005];
void a(int x){
if(x==0) return;
cout<<x<<" ";
a(l[x]);
a(r[x]);
}
void b(int x){
if(x==0) return;
b(l[x]);
cout<<x<<" ";
b(r[x]);
}
void c(int x){
if(x==0) return;
c(l[x]);
c(r[x]);
cout<<x<<" ";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++){
cin>>l[i]>>r[i];
}
a(1);
cout<<endl;
b(1);
cout<<endl;
c(1);
cout<<endl;
return 0;
}