From b320ee22311d414b12e2fb30c8cb60b1b214a239 Mon Sep 17 00:00:00 2001 From: Raghav Bajaj <73180455+Raghav-Bajaj@users.noreply.github.com> Date: Tue, 31 Oct 2023 19:51:43 +0530 Subject: [PATCH] Create leafNodeCount.java This program counts the leaf nodes in a binary tree --- Binary Tree/leafNodeCount.java | 44 ++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Binary Tree/leafNodeCount.java diff --git a/Binary Tree/leafNodeCount.java b/Binary Tree/leafNodeCount.java new file mode 100644 index 00000000000..264bd2bbb29 --- /dev/null +++ b/Binary Tree/leafNodeCount.java @@ -0,0 +1,44 @@ +class TreeNode { + int data; + TreeNode left; + TreeNode right; + + public TreeNode(int data) { + this.data = data; + left = null; + right = null; + } +} + +public class BinaryTree { + TreeNode root; + + public int countLeaves(TreeNode node) { + if (node == null) { + return 0; + } + + if (node.left == null && node.right == null) { + return 1; // Leaf node + } + + int leftLeaves = countLeaves(node.left); + int rightLeaves = countLeaves(node.right); + + return leftLeaves + rightLeaves; + } + + public static void main(String[] args) { + BinaryTree tree = new BinaryTree(); + tree.root = new TreeNode(1); + tree.root.left = new TreeNode(2); + tree.root.right = new TreeNode(3); + tree.root.left.left = new TreeNode(4); + tree.root.left.right = new TreeNode(5); + tree.root.right.left = new TreeNode(6); + tree.root.right.right = new TreeNode(7); + + int leaves = tree.countLeaves(tree.root); + System.out.println("Number of leaves in the binary tree: " + leaves); + } +}