-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinary Search Tree.cpp
71 lines (62 loc) · 1.18 KB
/
Binary Search Tree.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
#include <iostream>
#include <string>
using namespace std;
class Node{
public:
int data;
Node *left;
Node *right;
Node(int data){
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
Node *search(Node *root, int data){
if(root == NULL){
cout << "Not found" << endl;
return NULL;
}
if(root->data == data){
cout << "found at: " << root << endl;
return root;
}
if(root->data < data){
return search(root->right, data);
}else{
return search(root->left, data);
}
}
void insert(Node *root, int data){
if(root == NULL){
Node *root = new Node(data);
}else if(data <= root->data){
if(root -> left != NULL){
insert(root->left, data);
}else{
root -> left = new Node(data);
}
}else if(data > root->data){
if(root -> right != NULL){
insert(root->right, data);
}else{
root -> right = new Node(data);
}
}
}
int main(){
Node *root = new Node(5);
insert(root, 3);
insert(root, 8);
insert(root, 1);
insert(root, 4);
insert(root, 7);
insert(root, 9);
insert(root, 0);
insert(root, 2);
insert(root, 6);
insert(root, 10);
search(root, 10);
delete [] root;
return 0;
}