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.