二叉树的序遍历x(内含结构体与非结构体版x)

题目描述 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

分类标签 Tags 点此展开 

 

非结构体版x

 1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 int tree[30][2]= {0};
 6 
 7 void preorder(int node, int j) { //先序遍历
 8     if(tree[node][j]==0) return;
 9 
10     cout<<tree[node][j]<<" ";
11     preorder(tree[node][j], 0);
12     preorder(tree[node][j], 1);
13 }
14 
15 void inorder(int node, int j) { //中序遍历
16     if(tree[node][j]==0) return;
17 
18     inorder(tree[node][j], 0);
19     cout<<tree[node][j]<<" ";
20     inorder(tree[node][j], 1);
21 }
22 
23 void postorder(int node, int j) { //后序遍历
24     if(tree[node][j]==0) return;
25 
26     postorder(tree[node][j], 0);
27     postorder(tree[node][j], 1);
28 
29     cout<<tree[node][j]<<" ";
30 }
31 
32 int main() {
33     int n;//n<=16
34     cin>>n;
35     int i, j;
36     tree[0][0]=tree[0][1]=1;
37 
38     for (i = 1; i <= n; ++i)
39         for(j=0; j<2; j++)
40             cin>>tree[i][j];
41 
42     preorder(0, 0);
43     cout<<endl;
44     inorder(0, 0);
45     cout<<endl;
46     postorder(0, 0);
47     cout<<endl;
48     return 0;
49 }

结构体版x

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

如果运气好也是错,那我倒愿意错上加错!

❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀❀

原文地址:https://www.cnblogs.com/zxqxwnngztxx/p/6648212.html