SYBCom(CA) DS Practical Slip 7 Q.B

Write a C Program to find the product of all leaf nodes of a binary tree

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

// Structure of a binary tree node
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

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

// Function to create the binary tree
struct Node* createTree() {
    int data;
    printf("Enter data (-1 for no node): ");
    scanf("%d", &data);

    if (data == -1)
        return NULL;

    struct Node* node = createNode(data);

    printf("Enter left child of %d:\n", data);
    node->left = createTree();

    printf("Enter right child of %d:\n", data);
    node->right = createTree();

    return node;
}

// Function to find product of all leaf nodes
int productOfLeafNodes(struct Node* root) {
    if (root == NULL)
        return 1; // Multiplicative identity

    if (root->left == NULL && root->right == NULL)
        return root->data; // Leaf node

    return productOfLeafNodes(root->left) * productOfLeafNodes(root->right);
}

// Main function
int main() {
    struct Node* root = NULL;

    printf("Create Binary Tree:\n");
    root = createTree();

    int product = productOfLeafNodes(root);

    printf("Product of all leaf nodes: %d\n", product);

    return 0;
}
Spread the love

Leave a Comment

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

Scroll to Top