Dsa
Trees
Warm-up
Leaf Counting
Write a function that counts the number of leaf nodes in a binary tree. A leaf is a node that does not have any children.
Input format:
The first line contains an integer N, the number of nodes in the tree.
The next N lines contain three integers each: the node value, the left child value, and the right child value, where -1 indicates that the child does not exist.
Output format:
Output a single integer representing the number of leaf nodes in the tree.
Example:
Input:
5
1 2 3
2 4 -1
3 -1 -1
4 -1 -1
5 -1 -1
Output:
3
Key concepts
treesleavescounting
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now