Binary Search Tree (BST) in C : To Count nodes
Below is a simple C program that uses a binary search tree (BST) library to count the total number of nodes and the total number of leaf nodes in the tree. The program defines two functions:
count(T)
– Returns the total number of nodes in the BST.countLeaf(T)
– Returns the total number of leaf nodes in the BST.
#include <stdio.h>
#include <stdlib.h>
// Define the structure for 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 insert a node into the BST
struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}
// Function to count the total number of nodes in the BST
int count(struct Node* root) {
if (root == NULL) {
return 0;
}
return 1 + count(root->left) + count(root->right);
}
// Function to count the total number of leaf nodes in the BST
int countLeaf(struct Node* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
}
return countLeaf(root->left) + countLeaf(root->right);
}
// Main function
int main() {
struct Node* root = NULL;
// Insert nodes into the BST
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
// Count total nodes and leaf nodes
int totalNodes = count(root);
int totalLeafNodes = countLeaf(root);
// Display results
printf(“Total number of nodes in the BST: %d\n”, totalNodes);
printf(“Total number of leaf nodes in the BST: %d\n”, totalLeafNodes);
return 0;
}