Maximum Depth of Binary Tree

The maximum depth of a binary tree is the longest path from the root node to a leaf node.

In Java, the maximum depth of a binary tree can be calculated using a recursive algorithm.

One way to do this is to create a method that takes a node as an input and returns the maximum depth of the subtree rooted at that node. The method would then recursively call itself on the left and right children of the current node, and return the maximum of the two values plus one.

Here’s an example of a Java program that calculates the maximum depth of a binary tree:

class Node {
    int data;
    Node left;
    Node right;
    Node(int data) {
        this.data = data;
        left = null;
        right = null;
    }
}

class BinaryTree {
    Node root;
    int maxDepth(Node node) {
        if (node == null) {
            return 0;
        } else {
            int leftDepth = maxDepth(node.left);
            int rightDepth = maxDepth(node.right);
            return Math.max(leftDepth, rightDepth) + 1;
        }
    }
}

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("The maximum depth of the binary tree is: " + tree.maxDepth(tree.root));
    }
}
The maximum depth of the binary tree is: 3

Leave a Reply

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