C Program to Find the Product of All Leaf Nodes in a Binary Tree
In a Binary Tree, a leaf node is a node that does not have a left or right child. This program will calculate the product of all leaf nodes using recursion.
📝 Problem Statement
B) Write a C Program to find the product of all leaf nodes of a binary tree.
đź’ˇ Logic (Student-Friendly Steps)
- Define a structure for a binary tree node with:
dataleftpointerrightpointer
- Create the binary tree nodes (manually or using insertion logic).
- Write a recursive function
productOfLeaves:- If node is
NULL, return 1 (neutral element for multiplication). - If node is a leaf (both left and right are NULL), return its value.
- Otherwise, return the product of left and right subtrees.
- If node is
- Call the function from
main()and print the result.
đź’» Source Code (Student-Friendly)
#include <stdio.h>
#include <stdlib.h>
// Node structure
struct node
{
int data;
struct node *left;
struct node *right;
};
// Function to create a 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;
}
// Recursive function to find product of leaf nodes
int productOfLeaves(struct node* root)
{
if(root == NULL)
return 1;
if(root->left == NULL && root->right == NULL)
return root->data;
return productOfLeaves(root->left) * productOfLeaves(root->right);
}
int main()
{
struct node* root = NULL;
// Manually creating binary tree for simplicity
// Example tree:
// 2
// / \
// 3 5
// / \
// 4 6
root = createNode(2);
root->left = createNode(3);
root->right = createNode(5);
root->left->left = createNode(4);
root->left->right = createNode(6);
int product = productOfLeaves(root);
printf("Product of leaf nodes: %d\n", product);
return 0;
}
🖥️ Sample Output
Product of leaf nodes: 120
Explanation: Leaf nodes are 4, 6, and 5. Product = 4 Ă— 6 Ă— 5 = 120
🎓 Viva Questions with Answers
1. What is a leaf node?
A node with no left or right child.
2. Why do we return 1 for NULL nodes?
1 is the neutral element for multiplication, so it doesn’t affect the product.
3. How do we check if a node is a leaf?
If node->left == NULL && node->right == NULL.
4. What traversal is used here?
Preorder traversal logic is used recursively.
5. What is the time complexity of this program?
O(n), because each node is visited once.
