Site icon

Find minimum & maximum element in binary tree (recursive /java/ example)

Fig 1: Min & Max of binary tree

Let us look into couple of examples to find out largest & smallest element in a binary tree using java

Example 1: find maximum element in binary tree (recursive)

Fig 2: Max element in Tree

So, maximum value of Fig 2 is 80

Example 2: find maximum element in binary tree (DFS) using java

Fig 3: Maximum node value binary tree

We can calculate maximum value of binary tree using above algorithm. Similarly, we can find the minimum value in binary tree. Instead of finding the maximum value at any node, we will find the minimum value.
The time complexity of algorithm is O(n).

Program – find largest & smallest element in binary tree using java

1.) MaxMinElementInBTree Class:

package org.learn.Question;

public class MaxMinElementInBTree {

	public static int maxElementInBTree(Node root) {
		if (null == root)
			return Integer.MIN_VALUE;

		int currentNodeValue = root.data;
		int hLeftSub = maxElementInBTree(root.left);
		int hRightSub = maxElementInBTree(root.right);
		return Math.max(Math.max(hLeftSub, hRightSub), currentNodeValue);
	}

	public static int minElementInBTree(Node root) {
		if (null == root)
			return Integer.MAX_VALUE;

		int data = root.data;
		int left = minElementInBTree(root.left);
		int right = minElementInBTree(root.right);
		return Math.min(data, Math.min(left, right));
	}
}

2.) Node:

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.MaxMinElementInBTree;
import org.learn.Question.Node;

public class App {
	public static void main(String[] args) {
		// root level 0
		Node A = Node.createNode(60);
		// Level 1
		Node B = Node.createNode(50);
		Node C = Node.createNode(90);
		// Level 2
		Node D = Node.createNode(25);
		Node E = Node.createNode(80);
		Node F = Node.createNode(75);
		Node G = Node.createNode(45);

		// 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;

		int maxElement = MaxMinElementInBTree.maxElementInBTree(A);
		System.out.println("Maximum element in a binary tree: " + maxElement);

		int minElement = MaxMinElementInBTree.minElementInBTree(A);
		System.out.println("Minimum element in a binary tree: " + minElement);
	}
}

Output – minimum & maximum element in binary tree using java

Maximum element in a binary tree: 90
Minimum element in a binary tree: 25
Exit mobile version