-
Notifications
You must be signed in to change notification settings - Fork 617
/
searching_in_bst.cpp
109 lines (79 loc) · 2.28 KB
/
searching_in_bst.cpp
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
/*
Let’s say we want to search for the number, what we’ll do is we’ll start at the root, and then we will compare
the value to be searched with the value of the root if it’s equal we are done with the search if it’s lesser
we know that we need to go to the left subtree because in a binary search tree all the elements in the left
subtree are lesser and all the elements in the right subtree are greater. Searching an element in the
binary search tree is basically this traversal in which at each step we will go either towards left or right
and hence in at each step we discard one of the sub-trees. If the tree is balanced, we call a tree balanced if
for all nodes the difference between the heights of left and right subtrees is not greater than one,
we will start with a search space of ‘n’nodes and when we will discard one of the sub-trees
we will discard ‘n/2’ nodes so our search space will be reduced to ‘n/2’ and then in the next step
we will reduce the search space to ‘n/4’ and we will go on reducing like this till we find the element or
till our search space is reduced to only one node.
*/
#include<iostream>
using namespace std;
class node{
public:
int data;
node* left;
node* right;
// constructor
node(int x){
data = x;
left = nullptr;
right = nullptr;
}
};
node* Insert_into_bst(node* root, int data){
// make new node
if(root == nullptr){
root = new node(data);
return root;
}
else if(data < root->data){
root->left = Insert_into_bst(root->left,data);
}
else{
root->right = Insert_into_bst(root->right,data);
}
return root;
}
node* Create_BST(){
// root node
int data;
cin >> data;
node* root = nullptr;
while(data!= -1){
root = Insert_into_bst(root, data);
cin >> data;
}
return root;
}
bool search(node* root, int key){
if(root == nullptr)
return false;
if(root->data == key)
return true;
else if(root->data > key){
search(root->left, key);
}
else{
search(root->right, key);
}
}
int main(){
node* root = Create_BST();
int ele;
cin >> ele;
cout << boolalpha << search(root, ele);
return 0;
}
/*
Test Case :
Input : 1 2 3 4 5 6 -1
4
Outout : true
Time Complexity: O(n), in worst case (when BST is a right skew tree).
Space Complexity: O(n), for recursive stack.
*/