Site icon

Find maximum/ largest element in a binary tree ( java/ BFS / example)

Fig 1: Max element in binary tree

Example:  Maximum element in a binary tree using java

Fig 2: Max element at each level

Time complexity of algorithm is O(n).

Program: Maximum or largest element – binary tree

1.) MaxElement Class:

package org.learn.Question;

import java.util.LinkedList;
import java.util.Queue;

public class MaxElement {
	public static int maxElement(Node root) {
		if (root == null) {
			System.out.println("Tree is empty");
			return Integer.MIN_VALUE;
		}
		int max = root.data;
		Queue<Node> queue = new LinkedList<Node>();
		queue.offer(root);

		while (!queue.isEmpty()) {
			Node node = queue.poll();
			if(max < node.data) {
				max = node.data;
			}
			if (node.left != null) {
				queue.offer(node.left);
			}
			if (node.right != null) {
				queue.offer(node.right);
			}
		}
		System.out.println("Max Element in Binary Tree is : " + max);
		return max;
	}
}

2.) Node Class:

package org.learn.Question;

public class Node {
	public int data;
	public Node left;
	public Node right;

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

	public Node() {
		this.left = null;
		this.right = null;
	}
	
	public static Node createNode(int number) {
		return new Node(number);
	}
}

3.) App Class:

package org.learn.Client;

import org.learn.Question.MaxElement;
import org.learn.Question.Node;

public class App {
	public static void main(String[] args) {
		// root level 0
		Node A = Node.createNode(50);
		// Level 1
		Node B = Node.createNode(25);
		Node C = Node.createNode(30);
		// Level 2
		Node D = Node.createNode(40);
		Node E = Node.createNode(10);
		Node F = Node.createNode(30);
		Node G = Node.createNode(60);
		
		// connect Level 0 and 1
		A.left = B;
		A.right = C;
		// connect level 1 and level 2
		B.left = D;
		B.right = E;
		C.left = F;
		C.right = G;
		// connect level 2 and level 3
		MaxElement.maxElement(A);
	}
}

Output : maximum or largest element in binary tree (Java/BFS)

Max Element in Binary Tree is : 60

Code: maximum element binary tree non recursive (BFS)

Exit mobile version