EduLearn - Online Education Platform

Welcome to EduLearn!

Start learning today with our wide range of courses taught by industry experts. Gain new skills, advance your career, or explore new interests.

Browse Courses

Java Code: Count Leaf Nodes (Minimal Version)

Here is a short and simple Java code to count the number of leaf nodes in a binary tree using recursion:

 

βœ… Java Code: Count Leaf Nodes (Minimal Version

class Node {

int data;

Node left, right;

Node(int data) {

this.data = data;

}

}

 

public class CountLeafNodes {

 

int countLeaves(Node node) {

if (node == null) return 0;

if (node.left == null && node.right == null) return 1;

return countLeaves(node.left) + countLeaves(node.right);

}

 

public static void main(String[] args) {

Node root = new Node(10);

root.left = new Node(5);

root.right = new Node(15);

root.left.left = new Node(2);

root.right.right = new Node(20);

 

CountLeafNodes tree = new CountLeafNodes();

System.out.println(“Leaf nodes count: ” + tree.countLeaves(root));

}

}

πŸ“Œ Output:

Leaf nodes count: 2

πŸ’‘ Logic:

A node is a leaf if both left and right are null.

 

We add 1 when we find a leaf and recursively sum left and right.

 

 

 

Java Code: Count Leaf Nodes (Minimal Version)

Leave a Reply

Your email address will not be published. Required fields are marked *

EduLearn - Online Education Platform

Welcome to EduLearn!

Start learning today with our wide range of courses taught by industry experts. Gain new skills, advance your career, or explore new interests.

Browse Courses

Popular Courses

[Course Image]

Introduction to Programming

Learn the fundamentals of programming with Python in this beginner-friendly course.

12 Hours Beginner
[Course Image]

Data Science Essentials

Master the basics of data analysis, visualization, and machine learning.

20 Hours Intermediate
[Course Image]

Web Development Bootcamp

Build modern websites with HTML, CSS, JavaScript and popular frameworks.

30 Hours Beginner
[Course Image]

Digital Marketing Fundamentals

Learn SEO, social media marketing, email campaigns and analytics.

15 Hours Beginner
Educational Website Footer