-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBSTCreation.cpp
More file actions
81 lines (68 loc) · 1.3 KB
/
BSTCreation.cpp
File metadata and controls
81 lines (68 loc) · 1.3 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
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node *left;
Node *right;
Node(int data)
{
this->data = data;
left = right = NULL;
}
};
Node* insert(Node* root, int data)
{
if(root==NULL)
{
return new Node(data);
}
if(data < root->data)
{
root->left = insert(root->left, data);
}else{
root->right = insert(root->right, data);
}
return root;
}
void printInorder(Node *root)
{
if(root==NULL)
{
return;
}
printInorder(root->left);
cout << root->data << " ";
printInorder(root->right);
}
bool search(Node* root, int data)
{
if(root==NULL) return false;
if(root->data==data) return true;
if(data < root->data)
{
return search(root->left, data);
}
return search(root->right, data);
}
int main()
{
Node *root = NULL;
int a[] = {8, 3, 10, 1, 6, 14, 4, 7, 13};
for(int x : a)
{
root = insert(root, x);
}
printInorder(root);
cout << endl;
bool ans = search(root, 12);
if(ans==true)
{
cout << "Element exists";
}
if(ans==false)
{
cout << "Element doesn't exist";
}
return 0;
}