Sure! Below is a simple implementation of a Binary Search Tree (BST) in C++ using templates (generics). This allows the BST to store any data type that supports comparison operators (like <, >, ==).
🔧 Features included:
- Insertion
- Search
- In-order traversal (prints elements in sorted order)
📦 BST Implementation in C++ Using Templates:
#include <iostream>
template <typename T>
class BST {
private:
struct Node {
T data;
Node* left;
Node* right;
Node(const T& value) : data(value), left(nullptr), right(nullptr) {}
};
Node* root;
// Helper function for insertion
Node* insert(Node* node, const T& value) {
if (node == nullptr) {
return new Node(value);
}
if (value < node->data) {
node->left = insert(node->left, value);
} else if (value > node->data) {
node->right = insert(node->right, value);
}
// If value == node->data, do not insert duplicates
return node;
}
// Helper function for searching
bool search(Node* node, const T& value) const {
if (node == nullptr) return false;
if (value == node->data) return true;
else if (value < node->data) return search(node->left, value);
else return search(node->right, value);
}
// Helper function for in-order traversal
void inorder(Node* node) const {
if (node == nullptr) return;
inorder(node->left);
std::cout << node->data << " ";
inorder(node->right);
}
// Helper function to delete all nodes (destructor)
void destroyTree(Node* node) {
if (node == nullptr) return;
destroyTree(node->left);
destroyTree(node->right);
delete node;
}
public:
BST() : root(nullptr) {}
~BST() {
destroyTree(root);
}
void insert(const T& value) {
root = insert(root, value);
}
bool search(const T& value) const {
return search(root, value);
}
void inorder() const {
inorder(root);
std::cout << std::endl;
}
};
// Example usage
int main() {
BST<int> tree;
tree.insert(50);
tree.insert(30);
tree.insert(70);
tree.insert(20);
tree.insert(40);
tree.insert(60);
tree.insert(80);
std::cout << "In-order traversal: ";
tree.inorder(); // Output: 20 30 40 50 60 70 80
std::cout << "Search 40: " << (tree.search(40) ? "Found" : "Not Found") << std::endl;
std::cout << "Search 90: " << (tree.search(90) ? "Found" : "Not Found") << std::endl;
return 0;
}
📝 Notes:
- This implementation avoids inserting duplicate values.
- You can use this template with other comparable types like float, std::string, etc.
- For a complete BST, you might want to add deletion, balancing (e.g., AVL or Red-Black Tree), and other traversal methods.
Let me know if you'd like to add more features like deletion or balancing!