C# program to find min and max in binary search tree
Here's an example of a C# program that finds the minimum and maximum values in a binary search tree:
using System;
class Node
{
public int Data;
public Node Left;
public Node Right;
public Node(int data)
{
Data = data;
Left = null;
Right = null;
}
}
class BinarySearchTree
{
private Node root;
public void Insert(int data)
{
root = InsertRecursive(root, data);
}
private Node InsertRecursive(Node current, int data)
{
if (current == null)
{
return new Node(data);
}
if (data < current.Data)
{
current.Left = InsertRecursive(current.Left, data);
}
else if (data > current.Data)
{
current.Right = InsertRecursive(current.Right, data);
}
return current;
}
public int FindMin()
{
if (root == null)
{
throw new InvalidOperationException("Binary search tree is empty.");
}
Node current = root;
while (current.Left != null)
{
current = current.Left;
}
return current.Data;
}
public int FindMax()
{
if (root == null)
{
throw new InvalidOperationException("Binary search tree is empty.");
}
Node current = root;
while (current.Right != null)
{
current = current.Right;
}
return current.Data;
}
}
class Program
{
static void Main(string[] args)
{
BinarySearchTree bst = new BinarySearchTree();
// Inserting elements into the binary search tree
bst.Insert(50);
bst.Insert(30);
bst.Insert(20);
bst.Insert(40);
bst.Insert(70);
bst.Insert(60);
bst.Insert(80);
// Finding the minimum value in the binary search tree
int minValue = bst.FindMin();
Console.WriteLine("Minimum value in the binary search tree: " + minValue);
// Finding the maximum value in the binary search tree
int maxValue = bst.FindMax();
Console.WriteLine("Maximum value in the binary search tree: " + maxValue);
}
}
This program creates a binary search tree class ('BinarySearchTree') that contains a private 'Node' class. The 'Node' class represents each node in the binary search tree and holds the data and references to the left and right child nodes.
The 'BinarySearchTree' class provides two methods: 'FindMin' and 'FindMax'. The 'FindMin' method finds the minimum value in the binary search tree by traversing to the leftmost node (the node with the smallest value). The 'FindMax' method finds the maximum value in the binary search tree by traversing to the rightmost node (the node with the largest value).
In the 'Main' method, we create an instance of 'BinarySearchTree', insert elements into the binary search tree using the Insert method, and then call the 'FindMin' and 'FindMax' methods to find the minimum and maximum values in the tree, respectively. The program prints the results.
When you run this program, it will output the following:
Minimum value in the binary search tree: 20
Maximum value in the binary search tree: 80
This demonstrates the implementation of finding the minimum and maximum values in a binary search tree.