-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplementBSTArrays.cpp
145 lines (123 loc) · 2.8 KB
/
ImplementBSTArrays.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
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
145
#include <iostream>
#include <vector>
using namespace std;
//
class BinaryTree {
private:
vector<int> tree;
int MAX_SIZE;
public:
BinaryTree(int size) : MAX_SIZE(size) {
tree.resize(size, -1);
}
//
bool insert(int value) {
if (tree[0] == -1) {
tree[0] = value;
return true;
}
//
for (int i = 0; i < MAX_SIZE; ++i) {
if (tree[i] == -1) {
int parent_index = (i - 1) / 2;
if (i % 2 == 1) {
tree[i] = value;
return true;
} else {
tree[i] = value;
return true;
}
}
}
return false;
}
//
void display() {
cout << "Binary Tree:" << endl;
for (int i = 0; i < MAX_SIZE; ++i) {
if (tree[i] != -1) {
cout << tree[i] << " ";
} else {
cout << "- ";
}
}
cout << endl;
}
};
//
int main() {
BinaryTree binaryTree(15);
binaryTree.insert(5);
binaryTree.insert(3);
binaryTree.insert(7);
binaryTree.insert(1);
binaryTree.insert(4);
binaryTree.insert(6);
binaryTree.insert(9);
//
binaryTree.display();
//
return 0;
}
//
//
//
#include <iostream>
using namespace std;
// Define the structure for each node in the binary tree
struct Node {
int data;
Node* left;
Node* right;
};
// Function to create a new node
Node* createNode(int data){
Node* newNode = new Node();
newNode->data = data;
newNode->left = nullptr;
newNode->right = nullptr;
return newNode;
}
// Function to insert a new node in the binary tree
Node* insert(Node*root, int data){
if(root == NULL){
root = createNode(data);
}
else if(root->data <= data){
root->right = insert(root->right, data);
} else{
root->left = insert(root->left, data);
}
return root;
}
// Function to search for a node in the binary tree
bool search(Node*root,int data){
if(root==NULL) return false;
if(root->data == data){
return true;
} else if(root->data < data) {
return search(root->right, data);
} else{
return search(root->left, data);
}
return false;
}
void displayInorder(Node*root){
if(root==NULL) return ;
cout<<root->data<<" ";
displayInorder(root->left);
displayInorder(root->right);
}
int main() {
Node* root = nullptr;
root = insert(root, 10);
root = insert(root, 5);
root = insert(root, 15);
root = insert(root, 3);
root = insert(root, 7);
displayInorder(root);
cout<<endl;
cout << "Searching for 10: " << search(root, 10) << endl;
cout << "Searching for 20: " << search(root, 20) << endl;
return 0;
}