Skip to main content

Construct Binary Search Tree and find the min and max value of BST.

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;

}







Popular posts from this blog

Write a program to create a class Student2 along with two method getData (), printData () to get the value through argument and display the data in printData. Create the two objects s1, s2 to declare and access the values from class STtest.

 CODE: import java.util.Scanner; class Student2 {     private String name;     private int age;          // Method to set data     public void getData(String name, int age) {         this.name = name;         this.age = age;     }          // Method to print data     public void printData() {         System.out.println("Name: " + name);         System.out.println("Age: " + age);     } } public class STtest {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);                  // Creating objects of Student2 class         Student2 s1 = new Student2();         Student2 s2 = new Student2();              ...