Tutorialspoint
Problem
Solution
Submissions

Leaf Nodes in Binary Tree

Certification: Basic Level Accuracy: 100% Submissions: 1 Points: 8

Write a Java program to count the number of leaf nodes in a binary tree. A leaf node is a node that has no children (both left and right child pointers are null).

Example 1
  • Input: Binary tree [1,2,3,4,5]

    Binary Tree - Leaf Nodes have No Children

  • Output: 3
  • Explanation: Nodes 4, 5, and 3 are leaf nodes because they have no children.
Example 2
  • Input: Binary tree [1,null,2,3]

    Binary Tree - One Leaf Node Only


  • Output: 1
  • Explanation: Only node 3 is a leaf node.
Constraints
  • 0 ≤ Number of nodes ≤ 1000
  • -1000 ≤ Node.val ≤ 1000
  • Time Complexity: O(n) where n is the number of nodes
  • Space Complexity: O(h) where h is the height of the tree
Binary TreeGoldman SachsPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a recursive approach to traverse the tree
  • Check if a node is a leaf node (both left and right children are null)
  • Increment the count whenever a leaf node is encountered
  • Use pre-order, in-order, or post-order traversal to visit all nodes
  • Alternatively, you can use iterative traversal with a stack or queue

Steps to solve by this approach:

 Step 1: Check if the root is null. If it is, return 0.
 Step 2: Check if the current node is a leaf node (both left and right children are null).
 Step 3: If it's a leaf node, return 1.
 Step 4: If it's not a leaf node, recursively count leaf nodes in left and right subtrees.
 Step 5: Return the sum of leaf nodes from both subtrees.

Submitted Code :