C Program to Count the Number of Nodes in a Binary Tree

C Program to Count the Number of Nodes in a Binary Tree

Counting the total number of nodes in a binary tree is a fundamental operation in tree data structures. It helps in understanding the size of the tree, which is useful for performance analysis and in algorithms that require tree metrics. Both recursive and iterative methods can be used to count nodes efficiently.

Understanding the Problem

A binary tree consists of nodes connected via edges. To determine the total number of nodes, we must visit each node exactly once and increment a counter. Recursion provides a simple and elegant solution by counting the current node plus the nodes in the left and right subtrees. Iterative approaches, typically using a queue, process nodes level by level to achieve the same result.

Program 1: Recursive Approach

This program demonstrates how to count the total number of nodes using recursion. It adds one for the current node and then recursively counts nodes in the left and right subtrees.

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

// Structure for a tree node
typedef struct Node {
    int data;
    struct Node *left, *right;
} Node;

// Function to create a new node
Node* createNode(int value) {

    Node *newNode = (Node*)malloc(sizeof(Node));
    newNode->data = value;
    newNode->left = newNode->right = NULL;

    return newNode;

}

// Recursive function to count nodes
int countNodesRecursive(Node *root) {

    if (root == NULL)
        return 0;

    return 1 + countNodesRecursive(root->left) + countNodesRecursive(root->right);

}

int main() {

    Node *root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);
    root->right->left = createNode(6);
    root->right->right = createNode(7);

    printf("Total nodes (Recursive): %d\n", countNodesRecursive(root));

    return 0;

}

The recursive method ensures that every node is counted. It starts at the root and visits each subtree, summing the counts of left and right children while adding one for the current node.

Program 2: Iterative Approach (Using Queue)

This program uses a queue to count nodes iteratively by performing a level order traversal. Each node encountered increments a counter, and the final value represents the total number of nodes.

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

// Node structure
typedef struct Node {
    int data;
    struct Node *left, *right;
} Node;

// Queue structure
typedef struct Queue {
    Node **arr;
    int front, rear, size, capacity;
} Queue;

// Function to create a new node
Node* createNode(int value) {

    Node *newNode = (Node*)malloc(sizeof(Node));
    newNode->data = value;
    newNode->left = newNode->right = NULL;

    return newNode;

}

// Create a queue
Queue* createQueue(int capacity) {

    Queue *queue = (Queue*)malloc(sizeof(Queue));
    queue->capacity = capacity;
    queue->front = queue->size = 0;
    queue->rear = capacity - 1;
    queue->arr = (Node**)malloc(capacity * sizeof(Node*));

    return queue;

}

// Check if queue is empty
int isQueueEmpty(Queue *queue) {
    return (queue->size == 0);
}

// Enqueue
void enqueue(Queue *queue, Node *item) {

    if (queue->size == queue->capacity) return;

    queue->rear = (queue->rear + 1) % queue->capacity;
    queue->arr[queue->rear] = item;
    queue->size++;

}

// Dequeue
Node* dequeue(Queue *queue) {

    if (isQueueEmpty(queue)) return NULL;

    Node *item = queue->arr[queue->front];
    queue->front = (queue->front + 1) % queue->capacity;
    queue->size--;

    return item;

}

// Iterative function to count nodes
int countNodesIterative(Node *root) {

    if (!root) return 0;

    Queue *queue = createQueue(100);
    enqueue(queue, root);
    int count = 0;

    while (!isQueueEmpty(queue)) {

        Node *current = dequeue(queue);
        count++;

        if (current->left) enqueue(queue, current->left);

        if (current->right) enqueue(queue, current->right);

    }

    free(queue->arr);
    free(queue);

    return count;

}

int main() {

    Node *root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);
    root->right->left = createNode(6);
    root->right->right = createNode(7);

    printf("Total nodes (Iterative): %d\n", countNodesIterative(root));

    return 0;

}

This iterative approach counts nodes while performing a breadth-first traversal. By incrementing the counter for every dequeued node, we efficiently calculate the total number of nodes without using recursion.

FAQs

Q1: What is the time complexity of counting nodes?
The time complexity is O(n) for both recursive and iterative approaches because each node is visited exactly once.

Q2: Can we count nodes without using recursion or a queue?
Yes, a depth-first traversal using a stack can also be used to count nodes iteratively.

Q3: Does an empty tree count as a node?
No, an empty tree has zero nodes.

Q4: Is counting nodes the same as calculating tree size?
Yes, in a binary tree, the total number of nodes is also referred to as the tree’s size.

Conclusion

Counting nodes in a binary tree is a fundamental operation for understanding tree size and for algorithms that require knowledge of tree structure. Both recursive and iterative approaches are simple, effective, and linear in time complexity. Mastering both methods gives flexibility depending on whether you prefer recursion or level order iteration.

References & Additional Resources

A curated collection of books and online resources covering node counting, traversal methods, and properties of binary trees in C.

  1. Thareja, R. (2011). Data Structures Using C. Oxford University Press – Comprehensive coverage of binary tree structures, node counting, and traversal algorithms in C.
  2. Programiz: Binary Tree Traversals and Properties – Beginner-friendly guide explaining node operations, traversals, and tree properties.
  3. GeeksforGeeks: Count Nodes in a Binary Tree – Step-by-step explanation with C code examples.
Scroll to Top