-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreetraversal.c
95 lines (77 loc) · 1.63 KB
/
treetraversal.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <stdlib.h>
struct node
{
int value;
struct node* left;
struct node* right;
};
struct node* root;
struct node* insert(struct node* r, int data);
void inOrder(struct node* r);
void preOrder(struct node* r);
void postOrder(struct node* r);
int main()
{
root = NULL;
int n, v,i;
printf("How many data's do you want to insert ?\n");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Data %d: ", i+1);
scanf("%d", &v);
root = insert(root, v);
}
printf("Inorder Traversal: ");
inOrder(root);
printf("\n");
printf("Preorder Traversal: ");
preOrder(root);
printf("\n");
printf("Postorder Traversal: ");
postOrder(root);
printf("\n");
return 0;
}
struct node* insert(struct node* r, int data)
{
if(r==NULL)
{
r = (struct node*) malloc(sizeof(struct node));
r->value = data;
r->left = NULL;
r->right = NULL;
}
else if(data < r->value){
r->left = insert(r->left, data);
}
else {
r->right = insert(r->right, data);
}
return r;
}
void inOrder(struct node* r)
{
if(r!=NULL){
inOrder(r->left);
printf("%d ", r->value);
inOrder(r->right);
}
}
void preOrder(struct node* r)
{
if(r!=NULL){
printf("%d ", r->value);
preOrder(r->left);
preOrder(r->right);
}
}
void postOrder(struct node* r)
{
if(r!=NULL){
postOrder(r->left);
postOrder(r->right);
printf("%d ", r->value);
}
}