-
Notifications
You must be signed in to change notification settings - Fork 0
/
binarySearchTree.c
92 lines (76 loc) · 1.65 KB
/
binarySearchTree.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
//*
//BinaryTree implementation using recursion
//(C) Stephen Carter
//stephen.carter@mail.mcgill.ca
//
#include <stdlib.h>
#include <stdio.h>
typedef struct node{
int key;
struct node *left;
struct node *right;
}node;
void destroyTree(node *in){
if(in != 0){
destroyTree(in->left);
destroyTree(in->right);
free(in);
}
}
void insert(int key_in, node **start){
if(*start == 0){
*start = malloc(sizeof(node));
(*start)->key = key_in;
(*start)->left = 0;
(*start)->right = 0;
}else if(key_in < (*start)->key){
insert(key_in, &(*start)->left);
}else if(key_in > (*start)->key){
insert(key_in, &(*start)->right);
}
}
node *search(int key, node *start){
if(start != 0){
if(key == start->key)
return start;
else if(key < start->key)
return search(key, start->left);
else if(key > start->key)
return search(key, start->right);
}else
return 0;
}
void printPreorder(node *root){
if(root != 0){
printf("%d\n", root->key);
printPreorder(root->left);
printPreorder(root->right);
}
}
void printInorder(node *root){
if(root != 0){
printInorder(root->left);
printf("%d\n", root->key);
printInorder(root->right);
}
}
void printPostorder(node *root){
if(root != 0){
printPostorder(root->left);
printPostorder(root->right);
printf("%d\n", root->key);
}
}
int main(int argc, char** argv){
node *root = NULL;
insert(5, &root);
insert(10, &root);
insert(8, &root);
insert(3, &root);
insert(4, &root);
printPreorder(root);
printInorder(root);
printPostorder(root);
printf("%d was found\n", (search(8, root)->key));
destroyTree(root);
}