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
6d

Count the number of leaf nodes in a binary tree where each node has at most two children.

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

  • Use recursion to check each node in the tre...read more

Help your peers!
Add answer anonymously...
Samsung Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

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

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter