Google News
logo
Java program to find the largest element in a Binary Tree
In the following example of Java program to find the largest element in a Binary Tree :
Program :
public class BinaryTree {
    private TreeNode root;

    private static class TreeNode {
        private int data;
        private TreeNode left;
        private TreeNode right;

        public TreeNode(int data) {
            this.data = data;
            this.left = null;
            this.right = null;
        }
    }

    public void insert(int data) {
        root = insertNode(root, data);
    }

    public TreeNode insertNode(TreeNode root, int data) {
        if (root == null) {
            root = new TreeNode(data);
            return root;
        }

        if (data < root.data) {
            root.left = insertNode(root.left, data);
        } else if (data > root.data) {
            root.right = insertNode(root.right, data);
        }

        return root;
    }

    public int findLargest() {
        if (root == null) {
            System.out.println("Binary Tree is empty");
            return Integer.MIN_VALUE;
        }

        TreeNode current = root;
        while (current.right != null) {
            current = current.right;
        }

        return current.data;
    }

    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        tree.insert(50);
        tree.insert(30);
        tree.insert(70);
        tree.insert(20);
        tree.insert(40);
        tree.insert(60);
        tree.insert(80);

        int largest = tree.findLargest();
        System.out.println("Largest element in the Binary Tree is: " + largest);
    }
}
Output :
Largest element in the Binary Tree is: 80
In this program, we first define a Binary Tree class with a nested TreeNode class. The insert() method is used to insert nodes into the Binary Tree. The findLargest() method is used to find the largest element in the Binary Tree. It returns Integer.MIN_VALUE if the Binary Tree is empty.

To find the largest element, we start traversing from the root of the Binary Tree and keep going to the right until we reach the rightmost element, which will be the largest element in the Binary Tree.

In the main() method, we create a Binary Tree, insert some nodes, and then call the findLargest() method to find the largest element in the Binary Tree.