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.