-
Notifications
You must be signed in to change notification settings - Fork 2
/
search_bst.c
144 lines (116 loc) · 2.69 KB
/
search_bst.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
/****************************************************************************
File name: search_bst.c
Author: babajr
*****************************************************************************/
/*
Binary Search Tree (BST).
Search particular node in the BST, if present return its address,
else return NULL.
*/
#include <stdio.h>
#include <stdlib.h>
struct BstNode
{
struct BstNode *left;
int data;
struct BstNode *right;
};
typedef struct BstNode Node;
// create global root pointer
Node *root = NULL;
/*
API to create new node.
*/
Node *getNewNode(int value)
{
// create new node.
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->left = NULL;
newNode->data = value;
newNode->right = NULL;
return newNode;
}
/*
API to insert the nodes in order to create the BST.
Recursive Insert function is used.
Assumption: BST do not contain the duplicate values, so if value
is already present, it will not be added.
*/
Node *insert(Node *ptr, int value)
{
// If BST is empty, create the new node and insert it as root node.
if(ptr == NULL)
ptr = getNewNode(value);
// If nodes are present in the tree, then check for appropriate position to
// enter the node.
else if(value < ptr->data) // If duplicate is allowed else if(value <= ptr->data)
{
ptr->left = insert(ptr->left, value);
}
else
{
ptr->right = insert(ptr->right, value);
}
return ptr;
}
/*
API to display the tree in INORDER fashion.
*/
void printInorder(Node *ptr)
{
// Tree is empty.
if(ptr == NULL)
return;
printInorder(ptr->left);
printf("%d -> ", ptr->data);
printInorder(ptr->right);
}
/*
API to count the number of nodes in the tree.
*/
Node *search(Node *ptr, int key)
{
if(ptr == NULL)
{
return NULL;
}
if(key == ptr->data)
return ptr;
else if(key < ptr->data)
return search(ptr->left, key);
else
return search(ptr->right, key);
}
Node *searchIterative(Node *ptr, int key)
{
while(ptr != NULL)
{
if(ptr->data == key)
return ptr;
else if(ptr->data < key)
ptr = ptr->right;
else
ptr = ptr->left;
}
return NULL;
}
int main(void)
{
root = insert(root, 30); // create the root node.
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 50);
root = insert(root, 10);
root = insert(root, 25);
root = insert(root, 35);
printInorder(root);
printf("\n");
int key = 10;
Node *res = search(root, key);
// Node *res = searchIterative(root, key);
if(res != NULL)
printf("FOUND");
else
printf("NOT FOUND");
return 0;
}