DSA Series Chapter 22 – COUNT LEAF NODES IN BINARY TREE(Python Edition)


DSA Series Chapter 22 – COUNT LEAF NODES IN BINARY TREE(Python Edition)

1. Objective

To count the total number of leaf nodes in a Binary Tree using a recursive Depth First Search (DFS) approach implemented in Python.


2. Definition (Exam-Ready)

A leaf node is a node in a binary tree that has no left child and no right child.


3. Example Binary Tree

            1
          /   \
         2     3
        / \
       4   5

Leaf Nodes

  • Leaf nodes: 4, 5, 3

  • Leaf Count = 3


4. Condition to Identify Leaf Node

node.left is None AND node.right is None

5. Core Logic

  • If the tree is empty → return 0

  • If current node is a leaf → return 1

  • Otherwise:

    • Count leaf nodes in left subtree

    • Count leaf nodes in right subtree

    • Add the results


6. Recursive Formula

leafCount(node) =
    0                              if node is None
    1                              if node is a leaf
    leafCount(left) + leafCount(right) otherwise

7. Binary Tree Node Class

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

8. Function to Count Leaf Nodes

def count_leaf_nodes(root):
    if root is None:
        return 0

    if root.left is None and root.right is None:
        return 1

    return count_leaf_nodes(root.left) + count_leaf_nodes(root.right)

9. Line-by-Line Explanation

def count_leaf_nodes(root):
  • Function receives the root node of the tree


if root is None:
    return 0
  • Base case

  • Empty subtree has no leaf nodes


if root.left is None and root.right is None:
    return 1
  • Checks whether current node is a leaf

  • If yes, count it as one leaf


return count_leaf_nodes(root.left) + count_leaf_nodes(root.right)
  • Recursively counts leaf nodes in both subtrees

  • Adds both counts


10. Complete Python Program

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


def count_leaf_nodes(root):
    if root is None:
        return 0

    if root.left is None and root.right is None:
        return 1

    return count_leaf_nodes(root.left) + count_leaf_nodes(root.right)


# Driver Code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print("Total leaf nodes:", count_leaf_nodes(root))

11. Output

Total leaf nodes: 3

12. Time and Space Complexity

Time Complexity

  • O(n)
    Every node is visited once.

Space Complexity

  • O(h) (recursive call stack)

    • Balanced tree → O(log n)

    • Skewed tree → O(n)


13. Important Exam Points

  • Leaf node has degree 0

  • DFS recursion is most commonly used

  • Works for all binary trees (not BST-specific)

  • Root can also be a leaf if it has no children


14. Common Beginner Mistakes

  • Counting nodes with only one child as leaf

  • Forgetting the base case

  • Using global counters unnecessarily

  • Mixing leaf node logic with total node logic


15. Comparison: C vs Python

AspectCPython
NULL checkroot == NULLroot is None
MemoryManualAutomatic
RecursionFunction callsFunction calls

16. Learning Outcome

After completing this post, learners can:

  • Correctly identify leaf nodes

  • Implement leaf node counting in Python

  • Solve exam and interview questions

  • Extend logic to internal node counting

ALSO CHECK 

DS(Data Structure) Python&C Edition

DSA Series Chapter 1 Time & Space Complexity ( C Edition)

DSA Series Chapter 2 Arrays  (C Version)


DSA Series Chapter 2 Arrays  (Python Version)

DSA Series Chapter 3 Strings (C Version)


DSA Series Chapter 3 Strings (Python Version)


DSA Series Chapter 4 Linked Lists (Python Version)


DSA Series Chapter 4 Linked Lists (C Version)


DSA Series Chapter 5 Stacks (Python Version)


DSA Series Chapter 5  Stacks  (C Version)




















DSA Series Chapter 13 - Binary Tree traversal, BFS, DFT/DFS, Preorder Traversal In Binary Tree


DSA Series Chapter 14 - InOrder Traversal (Binary Tree C Version)


DSA Series Chapter 14 - InOrder Traversal (Binary Tree Python Version)

 

DSA Series Chapter 15 – POSTORDER TRAVERSAL (BINARY TREE)(Python Version)


DSA Series Chapter 15 – POSTORDER TRAVERSAL (BINARY TREE)(C Version)


DSA Series Chapter 16 – LEVEL ORDER TRAVERSAL(BINARY TREE BFS)(C Version)


DSA Series Chapter 16 – LEVEL ORDER TRAVERSAL(BINARY TREE BFS)(Python Version)



DSA Series Chapter 19 : DELETION IN BINARY TREE(C Version)

DSA Series Chapter 19 : DELETION IN BINARY TREE(Python Version)


DSA Series Chapter 20 – HEIGHT OF BINARY TREE(C Version)

DSA Series Chapter 20 – HEIGHT OF BINARY TREE(Python Version)

DSA Series Chapter 21 : COUNT TOTAL NODES IN BINARY TREE(C Version)


DSA Series Chapter 22 : Count Leaf nodes in Binary Tree (C Version)

DSA Series Chapter 22 : Count Leaf nodes in Binary Tree (Python Version)






Tail Recursion Optimization: How Compilers Convert Recursion Into Iteration


Advanced Recursion: Memoization vs. Tabulation — The Deep Optimization Blueprint for Professionals


Advanced Sorting Algorithms: Merge Sort Internals — Merge Tree, Cache Behavior & Real Cost Analysis


Enjoyed this post? [Follow here] for daily coding insights


Comments