Size of a Binary Tree


Size of Binary Tree – GeeksforGeeks


Problem: Size of Binary Tree

Problem Statement

You are given a binary tree. Your task is to find the total number of nodes in the given binary tree.


Examples

Example 1

Input:

       1
     /   \
    2     3

Output: 3

Example 2

Input:

       1
     /   \
    2     3
   /
  4

Output: 4


Constraints


Intuition

To compute the size of a binary tree (i.e., number of nodes), we can traverse the entire tree and count each node.
This naturally leads to a recursive approach where the size of the tree is:

Size = 1 (root node) + size(left subtree) + size(right subtree)

Approach (Recursion using Induction – Base Case – Hypothesis)

1. Base Case:

If the node is null, return 0 (size of an empty tree is 0).

2. Hypothesis:

Assume size(left) and size(right) correctly give the number of nodes in the left and right subtrees.

3. Induction:

Return 1 + size(left) + size(right) — counting the current node.


Code (Java)

class Tree {
    // Function to get the size of a binary tree
    int getSize(Node node) {
        // Base case
        if (node == null) return 0;

        // Hypothesis
        int leftSize = getSize(node.left);
        int rightSize = getSize(node.right);

        // Induction
        return 1 + leftSize + rightSize;
    }
}

Time and Space Complexity


Dry Run

Input:

    10
   /  \
  20   30
 /
40

Recursive stack:


Conclusion

This is a classic recursion problem that teaches: