-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This program counts the leaf nodes in a binary tree
- Loading branch information
1 parent
5fd3dcc
commit b320ee2
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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); | ||
} | ||
} |