Count Leaf Nodes in a Binary Tree

Given a binary tree, your task is to count and return the number of leaf nodes present in it.

A binary tree is a data structure where each node has at most two children, referred to as the left child and the right child. A leaf node is a node with both left and right child nodes as NULL.

Input:

The first line contains an integer 'T', representing the number of test cases. For each test case, you are given the elements of the binary tree in level order format. Each value of a node is separated by a space on a single line. Use -1 to represent a NULL node.

Output:

For each test case, return the count of leaf nodes 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:
The tree formed by the example input is:
Level 1: 20
Level 2: / \
10 35
Level 3: / \ / \
5 15 30 42
Level 4: / | |
13 (null)
Leaf nodes: 5, 30, 42, 13

Constraints:

  • 1 ≤ T ≤ 100
  • 1 ≤ N ≤ 10^3, where N is the number of nodes in the tree
  • 1 ≤ data ≤ 10^9
  • Time Limit: 1 sec
Note:
Input format is intended to provide clarity on how the binary tree is represented. The sequence will be given in a single line separated by spaces. You only need to implement the function to calculate the leaf nodes, printing will be handled elsewhere.
AnswerBot
8d

Count and return the number of leaf nodes in a binary tree.

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

  • Use recursion to traverse the tree efficiently.

  • Leaf nodes ...read more

Help your peers!
Add answer anonymously...
Ola Cabs Software Developer 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