Java Code: Find Maximum Element in Binary Tree
// Node class definition
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
public class BinaryTreeMax {
// Function to find the maximum element in the binary tree
int findMax(Node node) {
if (node == null)
return Integer.MIN_VALUE;
// Recursively find max in left and right subtrees
int leftMax = findMax(node.left);
int rightMax = findMax(node.right);
// Return the maximum among current node, leftMax and rightMax
return Math.max(node.data, Math.max(leftMax, rightMax));
}
public static void main(String[] args) {
BinaryTreeMax tree = new BinaryTreeMax();
// Example binary tree:
// 10
// / \
// 20 30
// / \ \
// 5 40 25
Node root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(5);
root.left.right = new Node(40);
root.right.right = new Node(25);
int max = tree.findMax(root);
System.out.println(“Maximum element in the binary tree is: ” + max);
}
}
๐ Output:
Maximum element in the binary tree is: 40
๐ก Explanation:
This code uses post-order traversal to check left and right subtrees.
Math.max() is used to compare and find the largest value.