Python Program to count nodes in a binary tree

In this article, we are going to learn how we can count the total number of nodes in a binary tree in Python, using different approaches. A binary tree is a data structure in which each node can have at most two children. The two children node of a binary tree are called the left child and the right child. We have to calculate the total number of nodes present in the binary tree.

Problem Examples

Scenario 1

<b>Input:</b> Binary Tree = 1 2 3 4 5
<b>Output:</b> Total number of nodes: 5

Above-given binary tree has five nodes: 1, 2, 3, 4, and 5.

Scenario 2

<b>Input:</b> 10 20 30 40 50 60
<b>Output:</b> Total number of nodes: 6

The binary tree has six nodes: 10, 20, 30, 40, 50, and 60.

Using the Recursive Approach

This is the direct approach, which involves recursively traversing the binary tree and counting all the nodes. We calculate the total nodes by counting the current node and then recursively counting the nodes present in its left and right subtrees ?

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def countNodes(root):
    if root is None:
        return 0
    left_count = countNodes(root.left)
    right_count = countNodes(root.right)
    return 1 + left_count + right_count

# Create binary tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print("Total number of nodes:", countNodes(root))
Total number of nodes: 5

Time Complexity: O(n) where n is the number of nodes.

Space Complexity: O(h) where h is the height of the tree due to recursion stack.

Using the Iterative Approach

In this approach, we use an iterative method to count the total number of nodes using a queue. We follow the Breadth-First Search (BFS) traversal technique to traverse the binary tree level by level and count each node ?

from collections import deque

class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def countNodesIterative(root):
    if root is None:
        return 0
    
    queue = deque([root])
    count = 0
    
    while queue:
        node = queue.popleft()
        count += 1
        
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)
    
    return count

# Create binary tree
root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.left.left = Node(40)
root.right.left = Node(50)
root.right.right = Node(60)

print("Total number of nodes:", countNodesIterative(root))
Total number of nodes: 6

Time Complexity: O(n) where n is the number of nodes.

Space Complexity: O(w) where w is the maximum width of the tree.

Comparison of Methods

Method Time Complexity Space Complexity Best For
Recursive O(n) O(h) Simple implementation
Iterative (BFS) O(n) O(w) Avoiding recursion limit

Real-Life Applications

Database Systems

Binary trees are used in databases (B-trees) where counting nodes helps in storage optimization and query planning.

File Systems

Directory structures use tree-like organization. Counting nodes helps determine storage usage and structure analysis.

Algorithm Design

Node counting is essential in divide-and-conquer algorithms and helps in complexity analysis of tree-based operations.

Conclusion

Both recursive and iterative approaches effectively count binary tree nodes with O(n) time complexity. Choose recursive for simplicity or iterative to avoid stack overflow in deep trees.

Kickstart Your Career

Get certified by completing the course

Get Started