-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtree_orders.c
74 lines (68 loc) · 1.83 KB
/
tree_orders.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* ----------------------------------------------------------------------- *
*
* Author: Leandro Augusto Lacerda Campos <[email protected]>
*
* Data Structures and Algorithms Specialization,
* by University of California, San Diego,
* and National Research University Higher School of Economics
*
* Course 2: Data Structures
*
* Solution for Binary Tree Traversals Problem
*
* ----------------------------------------------------------------------- */
#include <stdio.h>
#define MAXLEN 100000
/*
* inorder: prints the key of each vertice in the in-order traversal of the
* tree.
*/
void inorder(unsigned int key[], int left[], int right[], int idx)
{
if (idx == -1)
return;
inorder(key, left, right, left[idx]);
printf("%u ", key[idx]);
inorder(key, left, right, right[idx]);
}
/*
* preorder: prints the key of each vertice in the pre-order traversal of the
* tree.
*/
void preorder(unsigned int key[], int left[], int right[], int idx)
{
if (idx == -1)
return;
printf("%u ", key[idx]);
preorder(key, left, right, left[idx]);
preorder(key, left, right, right[idx]);
}
/*
* postorder: prints the key of each vertice in the post-order traversal of
* the tree.
*/
void postorder(unsigned int key[], int left[], int right[], int idx)
{
if (idx == -1)
return;
postorder(key, left, right, left[idx]);
postorder(key, left, right, right[idx]);
printf("%u ", key[idx]);
}
int main()
{
unsigned int key[MAXLEN];
int left[MAXLEN], right[MAXLEN];
int i, n;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%u %d %d", &key[i], &left[i], &right[i]);
}
inorder(key, left, right, 0);
putchar('\n');
preorder(key, left, right, 0);
putchar('\n');
postorder(key, left, right, 0);
putchar('\n');
return 0;
}