EduLearn - Online Education Platform

Welcome to EduLearn!

Start learning today with our wide range of courses taught by industry experts. Gain new skills, advance your career, or explore new interests.

Browse Courses

Java Code: Height of Binary Tree

Here’s a simple Java program to find the height of a Binary Tree:

 

βœ… Java Code: Height of Binary Tree

// Definition for a binary tree node

class Node {

int data;

Node left, right;

 

public Node(int item) {

data = item;

left = right = null;

}

}

 

public class BinaryTreeHeight {

 

// Function to calculate height of binary tree

int height(Node node) {

if (node == null)

return 0;

else {

// Get the height of left and right subtrees

int leftHeight = height(node.left);

int rightHeight = height(node.right);

 

// Return the larger one plus 1 for current node

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

}

}

 

public static void main(String[] args) {

BinaryTreeHeight tree = new BinaryTreeHeight();

 

// Creating a sample binary tree:

// 1

// / \

// 2 3

// / \ /

// 4 5 6

 

Node root = new Node(1);

root.left = new Node(2);

root.right = new Node(3);

root.left.left = new Node(4);

root.left.right = new Node(5);

root.right.left = new Node(6);

 

System.out.println(“Height of binary tree is: ” + tree.height(root));

}

}

 

πŸ“Œ Output:

Height of binary tree is: 3

πŸ’‘ Explanation:

The height of a binary tree is the number of nodes along the longest path from the root node down to the farthest leaf node.

 

The algorithm uses recursion to traverse the tree and find the maximum depth.

 

 

Java Code: Height of Binary Tree

Leave a Reply

Your email address will not be published. Required fields are marked *

EduLearn - Online Education Platform

Welcome to EduLearn!

Start learning today with our wide range of courses taught by industry experts. Gain new skills, advance your career, or explore new interests.

Browse Courses

Popular Courses

[Course Image]

Introduction to Programming

Learn the fundamentals of programming with Python in this beginner-friendly course.

12 Hours Beginner
[Course Image]

Data Science Essentials

Master the basics of data analysis, visualization, and machine learning.

20 Hours Intermediate
[Course Image]

Web Development Bootcamp

Build modern websites with HTML, CSS, JavaScript and popular frameworks.

30 Hours Beginner
[Course Image]

Digital Marketing Fundamentals

Learn SEO, social media marketing, email campaigns and analytics.

15 Hours Beginner
Educational Website Footer