English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java other topics

Java program to calculate the number of leaf nodes in a tree

    Comprehensive Java Examples

In this example, we will learn how to calculate the number of leaf nodes in a tree using Java.

Example: Java program to calculate the number of leaf nodes in a tree

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
Calculate the Number of Leaf Nodes

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.

Recommended:

Comprehensive Java Examples