Write the recursive C function to count the number of nodes present in a binary tree

int count (struct node* t)
{
if(t)
{
int l, r;
l = count(t->left);
r=count(t->right);
return (1+l+r);
}
else
{
return 0;
}
}

Sure, here’s a recursive C function to count the number of nodes in a binary tree:

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

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

// Function to create a new node with the given data
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;
}

// Recursive function to count the number of nodes in a binary tree
int countNodes(struct Node* root) {
// Base case: if the tree is empty
if (root == NULL)
return 0;
// Recursively count nodes in left and right subtrees
else
return 1 + countNodes(root->left) + countNodes(root->right);
}

int main() {
// Create a sample binary tree
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);

// Call the function to count nodes
printf("Number of nodes in the binary tree: %d\n", countNodes(root));

return 0;
}

In this code:

  • The Node struct represents a node in the binary tree, containing data and pointers to its left and right children.
  • The createNode() function creates a new node with the given data.
  • The countNodes() function recursively counts the number of nodes in the binary tree by traversing the tree in a depth-first manner.
  • In the main() function, a sample binary tree is created, and the countNodes() function is called with the root of the tree.