Count Nodes in Binary Tree in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include <stdio.h>
#include <stdlib.h>
typedef struct N { int d; struct N *l, *r; } N;
N* n(int d) { N* t = malloc(sizeof(N)); t->d = d; t->l = t->r = NULL; return t; }
int cnt(N* r) { return r ? 1 + cnt(r->l) + cnt(r->r) : 0; }
int main() {
    N* r = n(1);
    r->l = n(2); r->r = n(3);
    r->l->l = n(4); r->l->r = n(5);
    printf("%d", cnt(r));
}

C Output

Input:  
        1
       / \
      2   3
     / \
    4   5  

Output:  
5


C++ Program

#include <iostream>
using namespace std;
struct N {
    int d; N *l, *r;
    N(int v): d(v), l(0), r(0) {}
};
int cnt(N* r) {
    return r ? 1 + cnt(r->l) + cnt(r->r) : 0;
}
int main() {
    N* r = new N(10);
    r->l = new N(5); r->r = new N(15);
    r->r->l = new N(12); r->r->r = new N(20);
    r->r->r->r = new N(25);
    cout << cnt(r);
}

C++ Output

Input:  
        10
       /  \
      5    15
          /  \
        12    20
                  \
                  25 

Output:  
6


JAVA Program

class N {
    int d; N l, r;
    N(int d) { this.d = d; }
}
public class Main {
    static int cnt(N r) {
        return r == null ? 0 : 1 + cnt(r.l) + cnt(r.r);
    }
    public static void main(String[] a) {
        N r = new N(7);
        r.l = new N(3); r.r = new N(9);
        r.r.r = new N(11);
        System.out.println(cnt(r));
    }
}

JAVA Output

Input:  
      7
     / \
    3   9
           \
           11 

Output:  
4


Python Program

class N:
    def __init__(s, d): s.d, s.l, s.r = d, None, None
def cnt(r):
    return 0 if not r else 1 + cnt(r.l) + cnt(r.r)

r = N(4)
r.l = N(2); r.r = N(6)
r.l.l = N(1); r.r.r = N(7)
print(cnt(r))

Python Output

Input:  
       4
      / \
     2   6
    /     \
   1       7 

Output:  

5



In-Depth Explanation
Example
The C example tree has nodes: 1, 2, 3, 4, 5.
We count using recursion:

Root itself → 1

Count in left subtree

Count in right subtree
Total = 1 (root) + count(left) + count(right)
Final result: 5

Real-Life Analogy
Consider a company hierarchy. If the CEO has 2 managers, and each manager has some employees, how many people in total? You recursively count:

1 CEO

Count of everyone under Manager 1

Count of everyone under Manager 2
That's the way nodes in a binary tree are counted!

Why It Matters
Node counting is a basic operation in:

Memory management (keeping track of allocations)

Hierarchical data modeling (such as XML trees)

Game development (decision trees)

AI and compilers (abstract syntax trees)
You can't reason about its size, balance, or optimize it correctly if you don't know how many elements a tree contains.

Learning Insights
This exercise teaches:

Recursion with a straightforward base case (if null → 0)

Postorder-style tree traversal: visit children first, then aggregate

A generic pattern for summing values from tree structures

It also solidifies your grasp of how tree-based recursion functions cleanly and efficiently.

Interview & Real-World Application
Interviewers include this to try:

Recursive thinking

Knowledge of trees

Handling base + recursive case

Clean tree walk code

Real-world applications are:

HTML/XML/JSON tag counts

Node counts in routing and pathfinding systems

Analyzing structure size in dynamic data models

Measuring the size of a structure in dynamic data models is another underlying algorithm that teaches you about recursion and how tree traversal interplays. With the most elegant and terse solutions in C, C++, Java, and Python given above — and each working with different trees — you now possess a powerful grasp of how trees are traversed and how data is summed. This idea is typically requested in interviews and utilized throughout software systems that work with hierarchies and structured information.