码迷,mamicode.com
首页 > 其他好文 > 详细

3143 二叉树的序遍历

时间:2017-04-04 20:13:43      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:silver   等级   输入   pad   using   节点   struct   one   text   

3143 二叉树的序遍历

 

时间限制: 1 s
空间限制: 32000 KB
题目等级 : 白银 Silver
 
 
 
题目描述 Description

求一棵二叉树的前序遍历,中序遍历和后序遍历

输入描述 Input Description

第一行一个整数n,表示这棵树的节点个数。

接下来n行每行2个整数L和R。第i行的两个整数Li和Ri代表编号为i的节点的左儿子编号和右儿子编号。

输出描述 Output Description

输出一共三行,分别为前序遍历,中序遍历和后序遍历。编号之间用空格隔开。

样例输入 Sample Input

5

2 3

4 5

0 0

0 0

0 0

样例输出 Sample Output

1 2 4 5 3

4 2 5 1 3

4 5 2 3 1

数据范围及提示 Data Size & Hint

n <= 16

 1 #include<iostream>
 2 using namespace std;
 3 #include<cstdio>
 4 struct tree{
 5     int l;
 6     int r;
 7 };
 8 tree s[10010];
 9 void qian(int x)
10 {
11     cout<<x<<" ";
12     if(s[x].l)qian(s[x].l);
13     if(s[x].r)qian(s[x].r);
14 }
15 void zhong(int x)
16 {
17     if(s[x].l)zhong(s[x].l);
18     cout<<x<<" ";
19     if(s[x].r)zhong(s[x].r);
20 }
21 void hou(int x)
22 {
23     if(s[x].l)hou(s[x].l);
24     if(s[x].r)hou(s[x].r);
25     cout<<x<<" ";
26 }
27 int main()
28 {
29     int n;
30     cin>>n;
31     for(int i=1;i<=n;++i)
32         scanf("%d%d",&s[i].l,&s[i].r);
33     qian(1);cout<<endl;
34     zhong(1);cout<<endl;
35     hou(1);
36     return 0;
37 }
 1 #include<iostream>
 2 using namespace std;
 3 #include<cstdio>
 4 struct tree{
 5     int l;
 6     int r;
 7 };
 8 tree s[10010];
 9 void qian(int x)
10 {
11     cout<<x<<" ";
12     if(s[x].l)qian(s[x].l);
13     if(s[x].r)qian(s[x].r);
14 }
15 void zhong(int x)
16 {
17     if(s[x].l)zhong(s[x].l);
18     cout<<x<<" ";
19     if(s[x].r)zhong(s[x].r);
20 }
21 void hou(int x)
22 {
23     if(s[x].l)hou(s[x].l);
24     if(s[x].r)hou(s[x].r);
25     cout<<x<<" ";
26 }
27 int main()
28 {
29     int n;
30     cin>>n;
31     for(int i=1;i<=n;++i)
32         scanf("%d%d",&s[i].l,&s[i].r);
33     qian(1);cout<<endl;
34     zhong(1);cout<<endl;
35     hou(1);
36     return 0;
37 }

 

3143 二叉树的序遍历

标签:silver   等级   输入   pad   using   节点   struct   one   text   

原文地址:http://www.cnblogs.com/mjtcn/p/6666159.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!