📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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: 3
Comments
Post a Comment
Leave Comment