EduLearn - Online Education Platform

Welcome to EduLearn!

Start learning today with our wide range of courses taught by industry experts. Gain new skills, advance your career, or explore new interests.

Browse Courses

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.

Java Code: Find Maximum Element in Binary Tree

Leave a Reply

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

EduLearn - Online Education Platform

Welcome to EduLearn!

Start learning today with our wide range of courses taught by industry experts. Gain new skills, advance your career, or explore new interests.

Browse Courses

Popular Courses

[Course Image]

Introduction to Programming

Learn the fundamentals of programming with Python in this beginner-friendly course.

12 Hours Beginner
[Course Image]

Data Science Essentials

Master the basics of data analysis, visualization, and machine learning.

20 Hours Intermediate
[Course Image]

Web Development Bootcamp

Build modern websites with HTML, CSS, JavaScript and popular frameworks.

30 Hours Beginner
[Course Image]

Digital Marketing Fundamentals

Learn SEO, social media marketing, email campaigns and analytics.

15 Hours Beginner
Educational Website Footer