Min & Max

PHOTO EMBED

Thu May 25 2023 16:04:08 GMT+0000 (Coordinated Universal Time)

Saved by @prachi

#include <stdio.h>
#include <stdlib.h>
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

struct Node* createNode(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->left = newNode->right = NULL;
    return newNode;
}

struct Node* insertNode(struct Node* root, int value) {
    if (root == NULL) {
        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;
}

int findMin(struct Node* root) {
    if (root == NULL) {
        printf("Error: Tree is empty\n");
        return -1; 
    }
    while (root->left != NULL) {
        root = root->left;
    }
    return root->data;
}

int findMax(struct Node* root) {
    if (root == NULL) {
        printf("Error: Tree is empty\n");
        return -1; 
    }
    while (root->right != NULL) {
        root = root->right;
    }
    return root->data;
}

void freeTree(struct Node* root) {
    if (root == NULL) {
        return;
    }
    freeTree(root->left);
    freeTree(root->right);
    free(root);
}

int main() {
    struct Node* root = NULL;
    int numNodes;
    int value;
    
    printf("Enter the number of nodes in the binary search tree: ");
    scanf("%d", &numNodes);
    
    printf("Enter the values of the nodes:\n");
    for (int i = 0; i < numNodes; i++) {
        scanf("%d", &value);
        root = insertNode(root, value);
    }
    
    int minVal = findMin(root);
    int maxVal = findMax(root);
    
    printf("Minimum value: %d\n", minVal);
    printf("Maximum value: %d\n", maxVal);
    freeTree(root);
    return 0;
}
content_copyCOPY