SYBCom(CA) DS Practical Slip 20 Q.B

Write a C Program to implement the following functions on Binary Search Tree
-To count leaf nodes.
– To count total number of nodes.

#include <stdio.h>
#include <stdlib.h>

// Structure for BST Node
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// Function to create new node
struct Node* createNode(int value) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

// Insert node into BST
struct Node* insert(struct Node* root, int value) {
    if (root == NULL)
        return createNode(value);

    if (value < root->data)
        root->left = insert(root->left, value);
    else if (value > root->data)
        root->right = insert(root->right, value);

    return root;
}

// Count total nodes
int countTotalNodes(struct Node* root) {
    if (root == NULL)
        return 0;

    return 1 + countTotalNodes(root->left) + countTotalNodes(root->right);
}

// Count leaf nodes
int countLeafNodes(struct Node* root) {
    if (root == NULL)
        return 0;

    if (root->left == NULL && root->right == NULL)
        return 1;

    return countLeafNodes(root->left) + countLeafNodes(root->right);
}

int main() {
    struct Node* root = NULL;
    int n, value;

    printf("Enter number of nodes: ");
    scanf("%d", &n);

    printf("Enter %d values:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &value);
        root = insert(root, value);
    }

    printf("\nTotal number of nodes: %d\n", countTotalNodes(root));
    printf("Number of leaf nodes: %d\n", countLeafNodes(root));

    return 0;
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top