Google News
logo
Python Program to Count the Number of Nodes in Binary Tree
In the following example of a Python program that counts the number of nodes in a binary tree :
Program :
class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

class BinaryTree:
    def __init__(self):
        self.root = None

    def insert(self, value):
        if self.root is None:
            self.root = Node(value)
        else:
            self._insert(value, self.root)

    def _insert(self, value, node):
        if value < node.value:
            if node.left is None:
                node.left = Node(value)
            else:
                self._insert(value, node.left)
        else:
            if node.right is None:
                node.right = Node(value)
            else:
                self._insert(value, node.right)

    def count_nodes(self):
        return self._count_nodes(self.root)

    def _count_nodes(self, node):
        if node is None:
            return 0
        else:
            return 1 + self._count_nodes(node.left) + self._count_nodes(node.right)

# Example usage
tree = BinaryTree()
tree.insert(5)
tree.insert(3)
tree.insert(7)
tree.insert(1)
tree.insert(4)
tree.insert(6)
tree.insert(8)

print("Number of nodes:", tree.count_nodes())
Output :
Number of nodes: 7
In the above example, the `Node` class and `BinaryTree` class are the same as in the previous example. The new method `count_nodes()` recursively counts the number of nodes in the binary tree, starting at the root node. The `_count_nodes()` method is a helper method that performs the actual recursion through the tree.

If the current node is `None`, the method returns 0, otherwise it returns 1 plus the number of nodes in the left subtree plus the number of nodes in the right subtree.

The example usage at the bottom of the program constructs a binary search tree with some example values, and then calls `count_nodes()` to count the number of nodes in the tree.