Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Count Number of Leaf Node in a Tree
A leaf node in a tree is a node that has no children. In this program, we'll create a tree structure and implement a method to count all leaf nodes using recursive traversal.
Understanding Leaf Nodes
A leaf node is identified by having an empty children list. We'll use a helper function to recursively traverse the tree and collect all leaf nodes ?
Tree Structure Implementation
class Tree_structure:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root_node(self, data):
self.key = data
def add_child(self, node):
self.children.append(node)
def search_val(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search_val(key)
if temp is not None:
return temp
return None
def count_leaf_nodes(self):
leaf_nodes = []
self.count_leaf_helper(leaf_nodes)
return len(leaf_nodes)
def count_leaf_helper(self, leaf_nodes):
if self.children == []:
leaf_nodes.append(self)
else:
for child in self.children:
child.count_leaf_helper(leaf_nodes)
# Create a simple tree example
root = Tree_structure(10)
child1 = Tree_structure(20)
child2 = Tree_structure(30)
child3 = Tree_structure(40)
root.add_child(child1)
root.add_child(child2)
child1.add_child(child3)
print("Number of leaf nodes:", root.count_leaf_nodes())
Number of leaf nodes: 2
How the Algorithm Works
The counting algorithm uses these steps:
- Base Case: If a node has no children, it's a leaf node
- Recursive Case: If a node has children, recursively check each child
- Collection: Add all leaf nodes to a list and return the count
Interactive Tree Builder
Here's a simplified version that builds a tree and counts leaf nodes ?
class TreeNode:
def __init__(self, data):
self.data = data
self.children = []
def add_child(self, child_node):
self.children.append(child_node)
def count_leaves(self):
if not self.children: # No children = leaf node
return 1
total_leaves = 0
for child in self.children:
total_leaves += child.count_leaves()
return total_leaves
# Example: Building a tree
# 1
# / \
# 2 3
# / / \
# 4 5 6
root = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node4 = TreeNode(4)
node5 = TreeNode(5)
node6 = TreeNode(6)
root.add_child(node2)
root.add_child(node3)
node2.add_child(node4)
node3.add_child(node5)
node3.add_child(node6)
print(f"Tree structure has {root.count_leaves()} leaf nodes")
print("Leaf nodes are: 4, 5, and 6")
Tree structure has 3 leaf nodes Leaf nodes are: 4, 5, and 6
Alternative Counting Method
Here's a more direct approach that returns the count without storing nodes ?
class SimpleTree:
def __init__(self, data):
self.data = data
self.children = []
def add_child(self, child):
self.children.append(child)
def leaf_count(self):
if len(self.children) == 0:
return 1
count = 0
for child in self.children:
count += child.leaf_count()
return count
# Create a tree with multiple levels
root = SimpleTree('A')
b = SimpleTree('B')
c = SimpleTree('C')
d = SimpleTree('D')
e = SimpleTree('E')
root.add_child(b)
root.add_child(c)
b.add_child(d)
b.add_child(e)
print(f"Total leaf nodes: {root.leaf_count()}")
Total leaf nodes: 3
Key Points
- A leaf node has no children (empty children list)
- Use recursive traversal to visit all nodes in the tree
- Count leaf nodes by checking if
children == [] - The algorithm has O(n) time complexity where n is the number of nodes
Conclusion
Counting leaf nodes in a tree requires recursive traversal to check each node's children. A node with an empty children list is considered a leaf node. This approach efficiently counts all leaf nodes in O(n) time complexity.
