English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to calculate the number of leaf nodes in a tree using Java.
class Node { int item; Node left, right; public Node(int key) { item = key; left = right = null; } } class Main { //Root of the tree Node root; Main() { root = null; } //Method to calculate the number of leaf nodes public static int countLeaf(Node node) { if(node == null) { return 0; } //If the left and right of the node are empty //It is a leaf node if (node.left == null && node.right == null) { return 1; } else { return countLeaf(node.left) + countLeaf(node.right); } } public static void main(String[] args) { //Create a Tree object Main tree = new Main(); //Create a tree node tree.root = new Node(5); tree.root.left = new Node(3); tree.root.right = new Node(8); //Create the left child's child node tree.root.left.left = new Node(2); tree.root.left.right = new Node(4); //Create the right child's child node tree.root.right.left = new Node(7); tree.root.right.right = new Node(9); //Call method to calculate the number of leaf nodes int leafNodes = countLeaf(tree.root); System.out.println("Total Number of Leaf Nodes = "); + leafNodes); } }
Output Result
Total Number of Leaf Nodes = 4
In the above example, we have implemented the tree data structure using Java. Here, we use recursion to calculate the number of leaf nodes in the tree.