Code:
#include <iostream>
using namespace std;
// Define the structure for the nodes of the BST
struct Node {
int data;
Node* left;
Node* right;
};
// Function to create a new node
Node* createNode(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->left = nullptr;
newNode->right = nullptr;
return newNode;
}
// Function to insert a new node into the BST
Node* insertNode(Node* root, int value) {
if (root == nullptr) {
return createNode(value);
}
if (value < root->data) {
root->left = insertNode(root->left, value);
} else if (value > root->data) {
root->right = insertNode(root->right, value);
}
return root;
}
// Function to find the minimum value in the BST
int findMin(Node* root) {
if (root == nullptr) {
cout << "BST is empty\n";
return -1; // Assuming -1 as a default value for an empty tree
}
while (root->left != nullptr) {
root = root->left;
}
return root->data;
}
// Function to find the maximum value in the BST
int findMax(Node* root) {
if (root == nullptr) {
cout << "BST is empty\n";
return -1; // Assuming -1 as a default value for an empty tree
}
while (root->right != nullptr) {
root = root->right;
}
return root->data;
}
int main() {
Node* root = nullptr;
// Example usage
root = insertNode(root, 10);
insertNode(root, 5);
insertNode(root, 15);
insertNode(root, 3);
insertNode(root, 8);
cout << "Minimum value in BST: " << findMin(root) << endl;
cout << "Maximum value in BST: " << findMax(root) << endl;
return 0;
}