-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTree.c
More file actions
134 lines (121 loc) · 2.35 KB
/
binaryTree.c
File metadata and controls
134 lines (121 loc) · 2.35 KB
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
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int value;
struct node* left;
struct node* right;
}node;
node* createNode(int value)
{
node* yeni;
yeni = malloc(sizeof(node));
yeni->value = value;
yeni->left = NULL;
yeni->right = NULL;
return yeni;
}
void addNode(int value, node* root)
{
if (root)
{
if (root->value < value)
{
if (root->right)
addNode(value, root->right);
else
{
node* yeni = createNode(value);
root->right = yeni;
}
}
else
{
if (root->left)
addNode(value, root->left);
else
{
node* yeni = createNode(value);
root->left = yeni;
}
}
}
else
{
root->value = value;
root->left = NULL;
root->right = NULL;
}
}
void search(int value, node* root)
{
int flag = 1;
if ( !root)
{
printf("List is empty \n");
}
else
{
node* current = root;
while ( (current) && (flag) )
{
if (current->value < value)
current = current-> right;
else if ( current-> value > value)
current = current->left;
else if ( current-> value == value)
{
printf("Element found \n");
flag = 0;
}
}
}
if (flag)
printf("Element is not in the tree \n");
}
void preOrder (node* root)
{
if (root)
{
printf("%d ", root-> value);
preOrder(root->left);
preOrder(root->right);
}
}
void postOrder(node* root)
{
if (root)
{
postOrder(root->left);
printf("%d ", root->value);
postOrder(root->right);
}
}
void inOrder(node* root)
{
if (root)
{
inOrder(root->left);
inOrder(root->right);
printf("%d ", root->value);
}
}
int main(int argc, char **argv)
{
node* root = createNode(9);
addNode(5, root);
addNode(12, root);
addNode(1, root);
addNode(10, root);
addNode(7, root);
addNode(4, root);
preOrder(root);
printf("\n");
postOrder(root);
printf("\n");
inOrder(root);
printf("\n");
search(4, root);
search(18, root);
return 0;
}