Count Leaf Nodes in a Binary Tree

Count the number of leaf nodes present in a given binary tree. A binary tree is a data structure where each node has at most two children, known as the left child and the right child. A node is considered a leaf node if both of its child nodes are NULL.

Input:

The first line of input contains an integer 'T', representing the number of test cases. Each test case consists of a line containing elements of the binary tree in level order. If a node is null, it is represented by -1.

Output:

For each test case, output the number of leaf nodes present in the binary tree.

Example:

Input:
1
20 10 35 5 15 30 42 -1 13 -1 -1 -1 -1 -1 -1 -1
Output:
4
Explanation:

In the above example, nodes 5, 30, 42, and 13 are leaf nodes because they have no child nodes.

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 10^3
  • 1 <= data <= 10^9
  • Time Limit: 1 second
AnswerBot
4mo

Count the number of leaf nodes in a binary tree.

  • Traverse the binary tree and count nodes with both children as NULL.

  • Use recursion to check each node in the tree.

  • Leaf nodes have no children, so their l...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Intern Interview Questions Asked at Samsung

Q. Suppose an array of length n sorted in ascending order is rotated between 1 and ...read more
Q. What are the ACID properties in DBMS?
Q. Largest Number in Binary Tree You are provided with a Binary Tree consisting of ...read more
Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits