How to Count the Number of Nodes in a Binary Tree in Python

In this tutorial, we will learn how to program “How to Count the Number of Nodes in a Binary Tree in Python.” The main objective is to understand the logic and approach behind counting the total number of nodes present in a binary tree. This tutorial will guide you step by step through the process of traversing the tree and calculating the node count efficiently. By the end of this tutorial, you will have a solid understanding of how binary trees work in Python, helping you strengthen your problem-solving abilities and improve your overall coding skills in data structure implementation.

This topic is straightforward and easy to understand. By simply following the instructions provided, you will be able to complete it with ease. The program will guide you step by step through the process of constructing a tree and performing various operations on it, such as insertion, traversal, and manipulation of nodes. So, let’s dive into the coding process and start implementing the solution to gain a deeper understanding of tree data structures in Python!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. class BinaryTree:
  2.     def __init__(self, key=None):
  3.         self.key = key
  4.         self.left = None
  5.         self.right = None
  6.  
  7.     def inorder(self):
  8.         if self.left:
  9.             self.left.inorder()
  10.         print(self.key, end=' ')
  11.         if self.right:
  12.             self.right.inorder()
  13.  
  14.     def insert_left(self, node):
  15.         self.left = node
  16.  
  17.     def insert_right(self, node):
  18.         self.right = node
  19.  
  20.     def search(self, key):
  21.         if self.key == key:
  22.             return self
  23.         if self.left:
  24.             found = self.left.search(key)
  25.             if found:
  26.                 return found
  27.         if self.right:
  28.             return self.right.search(key)
  29.         return None
  30.  
  31.  
  32. def count_nodes(node):
  33.     if node is None:
  34.         return 0
  35.     return 1 + count_nodes(node.left) + count_nodes(node.right)
  36.  
  37.  
  38. # MAIN PROGRAM
  39. while True:
  40.     print("\n================= Count the Number of Nodes in a Binary Tree =================\n")
  41.  
  42.     btree = None
  43.  
  44.     print("Menu (this assumes no duplicate keys)")
  45.     print("insert <data> at root")
  46.     print("insert <data> left of <data>")
  47.     print("insert <data> right of <data>")
  48.     print("count")
  49.     print("quit")
  50.  
  51.     while True:
  52.         print("\nInorder traversal:", end=" ")
  53.         if btree:
  54.             btree.inorder()
  55.         print()
  56.  
  57.         do = input("What would you like to do? ").split()
  58.         if not do:
  59.             continue
  60.  
  61.         operation = do[0].lower()
  62.  
  63.         if operation == "insert":
  64.             data = int(do[1])
  65.             new_node = BinaryTree(data)
  66.  
  67.             if do[2] == "at" and do[3] == "root":
  68.                 if btree is None:
  69.                     btree = new_node
  70.                 else:
  71.                     print("Root already exists.")
  72.  
  73.             elif do[2] in ("left", "right") and do[3] == "of":
  74.                 key = int(do[4])
  75.                 ref_node = btree.search(key) if btree else None
  76.  
  77.                 if ref_node is None:
  78.                     print("No such key.")
  79.                 else:
  80.                     if do[2] == "left":
  81.                         ref_node.insert_left(new_node)
  82.                     else:
  83.                         ref_node.insert_right(new_node)
  84.  
  85.         elif operation == "count":
  86.             print("Number of nodes in tree:", count_nodes(btree))
  87.  
  88.         elif operation == "quit":
  89.             break
  90.  
  91.         else:
  92.             print("Invalid command.")
  93.  
  94.     # Try again option
  95.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  96.     if opt == "no":
  97.         print("Exiting program...")
  98.         break
  99.     elif opt != "yes":
  100.         print("Invalid choice. Exiting program...")
  101.         break

This program demonstrates how a Binomial Heap works by implementing it from scratch in Python and providing a simple menu-driven interface for interaction. A binomial heap is a collection of binomial trees, where each tree follows the min-heap property and no two trees share the same order. The `BinomialTree` class represents an individual tree node, storing a key, its children, and its order, while the `BinomialHeap` class manages a list of these trees and handles heap operations. The program supports inserting new elements by creating a temporary heap and merging it with the current one, ensuring trees of the same order are combined correctly. It also allows retrieving the minimum element without removal and extracting the minimum element by removing the smallest root and reintegrating its children back into the heap. Through continuous user input, the program lets users perform insertions, view the minimum value, extract it, or exit, making it a clear and practical illustration of binomial heap operations and behavior.

Output:

There you have it we successfully created How to Count the Number of Nodes in a Binary Tree in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials