Description
给你一棵 n(1\le n\le 10)n(1≤n≤10) 个结点的二叉树,请你输出它的先序遍历、中序遍历、后序遍历
Format
Input
第一行一个正整数 nn,表示二叉树的结点个数,编号为 1\sim n1∼n。
第二行开始,连续 nn 行,每行三个正整数 u,l,ru,l,r,表示 uu 的左儿子 ll 和右儿子 rr,若没有儿子,则相应的位置为 00。
Output
输出 33 行,每行 nn 个正整数,分别表示该二叉树的先序遍历、中序遍历、后序遍历,中间用一个空格隔开。
Samples
输入数据 1
6
1 5 6
5 2 3
2 0 0
3 4 0
6 0 0
4 0 0
Copy
输出数据 1
1 5 2 3 4 6
2 5 4 3 1 6
2 4 3 5 6 1
Copy
Limitation
1s, 1024KiB for each test case.
首先分析,这道题肯定用结构体和递归。
结构体包含一个节点的左子树和右子树。
struct two{
int l,r;
}a[17];
接下来递归分三个,前序,中序和后序。
很简单,前序先输出根节点,然后左右子树分别调用自己就行了。
void s1(int i){
if(i==0)return;
cout<<i<<" ";
s1(a[i].l);
s1(a[i].r);
}
中序和后序也是一样。
void s2(int i){
if(i==0)return;
s2(a[i].l);
cout<<i<<" ";
s2(a[i].r);
}
void s3(int i){
if(i==0)return;
s3(a[i].l);
s3(a[i].r);
cout<<i<<" ";
}
主函数就很好写了,输入一个节点和他的左右儿子,然后调用函数就行。
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
int t;
cin>>t;
cin>>a[t].l>>a[t].r;
}
s1(1);
cout<<endl;
s2(1);
cout<<endl;
s3(1);
return 0;
}
看代码前先来段广告 :
此题来自沐枫oj,强烈建议大家去康康。
最后附上满分代码~
#include <bits/stdc++.h>
using namespace std;
struct two{
int l,r;
}a[17];
void s1(int i){//前序遍历
if(i==0)return;
cout<<i<<" ";
s1(a[i].l);
s1(a[i].r);
}
void s2(int i){//中序遍历
if(i==0)return;
s2(a[i].l);
cout<<i<<" ";
s2(a[i].r);
}
void s3(int i){//后序遍历
if(i==0)return;
s3(a[i].l);
s3(a[i].r);
cout<<i<<" ";
}
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
int t;
cin>>t;
cin>>a[t].l>>a[t].r;
}
s1(1);
cout<<endl;//不要忘记换行
s2(1);
cout<<endl;
s3(1);
return 0;
}
简简单单,轻轻松松~