Google News
logo
Java program to find the maximum depth or height of a tree
In the following example of Java program to find the maximum depth or height of a tree :
Program :
// Node class
class Node {
    int data;
    Node left, right;
    
    public Node(int data) {
        this.data = data;
        left = right = null;
    }
}

// Binary tree class
class BinaryTree {
    Node root;
    
    // Method to find the maximum depth or height of a tree
    public int maxDepth(Node node) {
        if (node == null) {
            return 0;
        } else {
            int leftDepth = maxDepth(node.left);
            int rightDepth = maxDepth(node.right);
            
            if (leftDepth > rightDepth) {
                return leftDepth + 1;
            } else {
                return rightDepth + 1;
            }
        }
    }
}

// Main class
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);
        
        int height = tree.maxDepth(tree.root);
        System.out.println("The maximum height of the binary tree is: " + height);
    }
}
Output :
The maximum height of the binary tree is: 3
In this program, we first define a Node class to represent a node in the binary tree. Then we define a BinaryTree class with a method called maxDepth that takes a node as an argument and returns the maximum depth or height of the tree.

In the maxDepth method, we first check if the given node is null, and if so, we return 0. Otherwise, we recursively calculate the maximum depth of the left and right subtrees, and return the maximum of the two plus 1. Finally, in the main method, we create a binary tree and call the maxDepth method to find its maximum height.