-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathTree Traversal.c
171 lines (134 loc) · 3.1 KB
/
Tree Traversal.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#include <stdio.h>
struct node
{
int data;
struct node *leftChild;
struct node *rightChild;
};
struct node *root = NULL;
void insert(int data)
{
struct node *tempNode = (struct node*) malloc(sizeof(struct node));
struct node *current;
struct node *parent;
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
if(root == NULL)
{
root = tempNode;
}
else
{
current = root;
parent = NULL;
while(1)
{
parent = current;
if(data < parent->data)
{
current = current->leftChild;
if(current == NULL)
{
parent->leftChild = tempNode;
return;
}
}
else
{
current = current->rightChild;
if(current == NULL)
{
parent->rightChild = tempNode;
return;
}
}
}
}
}
struct node* search(int data)
{
struct node *current = root;
printf("Visiting elements: ");
while(current->data != data)
{
if(current != NULL)
printf("%d ",current->data);
if(current->data > data)
{
current = current->leftChild;
}
else
{
current = current->rightChild;
}
if(current == NULL)
{
return NULL;
}
}
return current;
}
void pre_order_traversal(struct node* root)
{
if(root != NULL)
{
printf("%d ",root->data);
pre_order_traversal(root->leftChild);
pre_order_traversal(root->rightChild);
}
}
void inorder_traversal(struct node* root)
{
if(root != NULL)
{
inorder_traversal(root->leftChild);
printf("%d ",root->data);
inorder_traversal(root->rightChild);
}
}
void post_order_traversal(struct node* root)
{
if(root != NULL)
{
post_order_traversal(root->leftChild);
post_order_traversal(root->rightChild);
printf("%d ", root->data);
}
}
int main()
{
int i;
int array[7] = { 27, 14, 35, 10, 19, 31, 42 };
for(i = 0; i < 7; i++)
insert(array[i]);
i = 31;
struct node * temp = search(i);
if(temp != NULL)
{
printf("[%d] Element found.", temp->data);
printf("\n");
}
else
{
printf("[ x ] Element not found (%d).\n", i);
}
i = 15;
temp = search(i);
if(temp != NULL)
{
printf("[%d] Element found.", temp->data);
printf("\n");
}
else
{
printf("[ x ] Element not found (%d).\n", i);
}
printf("\nPreorder traversal: ");
pre_order_traversal(root);
printf("\nInorder traversal: ");
inorder_traversal(root);
printf("\nPost order traversal: ");
post_order_traversal(root);
return 0;
}