Skip to content

Commit

Permalink
Merge pull request #6989 from sulaemanahmed/patch-1
Browse files Browse the repository at this point in the history
Update leafNodeCount.java
  • Loading branch information
ossamamehmood authored Nov 1, 2023
2 parents 56c55ed + b22e01f commit 1c7fdcf
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions Binary Tree/leafNodeCount.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,38 @@ public int countLeaves(TreeNode node) {
return leftLeaves + rightLeaves;
}

public int getHeight(TreeNode node) {
if (node == null) {
return 0;
}

int leftHeight = getHeight(node.left);
int rightHeight = getHeight(node.right);

return Math.max(leftHeight, rightHeight) + 1;
}

public void inOrderTraversal(TreeNode node) {
if (node == null) {
return;
}

inOrderTraversal(node.left);
System.out.print(node.data + " ");
inOrderTraversal(node.right);
}

public int countNodes(TreeNode node) {
if (node == null) {
return 0;
}

int leftCount = countNodes(node.left);
int rightCount = countNodes(node.right);

return leftCount + rightCount + 1;
}

public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.root = new TreeNode(1);
Expand All @@ -38,7 +70,14 @@ public static void main(String[] args) {
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);
System.out.println("Number of leaves in the binary tree: " + tree.countLeaves(tree.root));
System.out.println("Height of the binary tree: " + tree.getHeight(tree.root));

System.out.print("In-order traversal of the binary tree: ");
tree.inOrderTraversal(tree.root);
System.out.println();

System.out.println("Total nodes in the binary tree: " + tree.countNodes(tree.root));
}
}

0 comments on commit 1c7fdcf

Please sign in to comment.