In this blog post, we will walk you through the process of writing a Java program to find the height of a binary tree.
1. Defining the Binary Tree Node:
The foundation of a binary tree is its nodes. Here's a simple class definition for a binary tree node:class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}2. Implementing the Binary Tree Class:
class BinaryTree {
Node root;
// Compute the height of the binary tree
int height(Node node) {
if (node == null) {
return 0;
} else {
// Compute the height of each subtree
int leftHeight = height(node.left);
int rightHeight = height(node.right);
// Return the larger one
return Math.max(leftHeight, rightHeight) + 1;
}
}
int getHeight() {
return height(root);
}
}3. Testing the Program:
public class Main {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("Height of the binary tree is: " + tree.getHeight());
}
}Height of the binary tree is: 3Step-by-Step Explanation:
Conclusion
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment