Write a program to find the node with the minimum value in a binary search tree and print it.
For example, if the input tree as below then output is 6 where 6 is a node with the minimum value in the whole tree.
Input:
6
10 5 6 7 8 9
Output:
5
Solution
import java.util.*;
class Node
{
int data;
Node left, right;
Node(int d)
{
data = d;
left = right = null;
}
}
class BinaryTree
{
static Node head;
Node insert(Node node, int data)
{
if (node == null)
{
return (new Node(data));
}
else
{
if (data <= node.data)
{
node.left = insert(node.left, data);
}
else
{
node.right = insert(node.right, data);
}
return node;
}
}
int minvalue(Node node)
{
//write your code here
if (node == null) {
return Integer.MAX_VALUE;
} else {
int minvalue = node.data;
int left = minvalue(node.left);
int right = minvalue(node.right);
if (left < minvalue) {
minvalue = left;
}
if (right < minvalue) {
minvalue = right;
}
return minvalue;
}
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
Node root = null;
Scanner s=new Scanner(System.in);
int n, i, num;
n=s.nextInt();
int arr[]=new int[n];
for(i = 0; i < n; i++)
{
arr[i] = s.nextInt();
}
for(i = 0; i < n; i++)
{
if(root == null)
{
root = tree.insert(root, arr[i]);
}
tree.insert(root, arr[i]);
}
System.out.println(tree.minvalue(root));
}
}
Happy Learning – If you require any further information, feel free to contact me.