To find the maximum element in a binary tree in Java, you can perform a depth-first search (DFS) traversal of the tree and keep track of the maximum value encountered. Here's how you can implement it:
class TreeNode {
int val;
TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}
}
public class MaximumElementInBinaryTree {
int max = Integer.MIN_VALUE;
public int findMax(TreeNode root) {
if (root == null) return Integer.MIN_VALUE;
max = Math.max(max, root.val);
findMax(root.left);
findMax(root.right);
return max;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
MaximumElementInBinaryTree finder = new MaximumElementInBinaryTree();
int maxElement = finder.findMax(root);
System.out.println("Maximum Element in Binary Tree: " + maxElement);
}
}
In this code:
- We define a
TreeNode
class to represent each node in the binary tree. - We create a class called
MaximumElementInBinaryTree
to find the maximum element. - Inside the
findMax
method, we perform a depth-first search (DFS) traversal of the tree recursively. - During traversal, we update the
max
variable whenever we encounter a node with a value greater than the current maximum. - Finally, we return the maximum element found in the binary tree.