If a node is NULL, the function returns 0. If both the left and right child nodes of the current node are NULL, it returns 1, indicating a leaf node. The count of leaf nodes from the left and right subtrees provide the total count leaf nodes.
Leaf count of a tree = Leaf count of left subtree + Leaf count of right subtree
If the node is NULL, return 0.
If the node has no left or right child, return 1.
Recursively call countLeaves() on the left and right child nodes if the node has left or right children, and then return the total of the results.
Output
3
Iterative Approach - O(n) Time and O(n) Space
The idea is to usethequeue basedlevel order traversal to efficiently count the leaf nodes in a binary tree. We check each node as it is dequeued from queue. For every node, we check if it has no left or right children, indicating that it is a leaf node, and increment our count accordingly.
Create a queue to traverse in level order manner and a variable count to keep track of the number of leaf nodes. Start by enqueuing the root node.
While the queue is not empty, proceed with the traversal.
Dequeue the front node from the queue and check its children.
If both the left and right children of the current node are NULL, increment the count variable by 1, indicating that a leaf node has been found.
If the current node has a left child, enqueue it into the queue. Similarly, if it has a right child, enqueue that child also.
Finally, return the count of leaf nodes found during the traversal.