This is a continuation of my post How to create a binary tree in c#.In this post, I will show you how to find max or min value in a given binary tree.
Min Value: Loop down to find the leftmost leaf
Max Value: Loop down to find the rightmost leaf
public int FindMinValue()
{
return FindMinValue(_root);
}
private int FindMinValue(Node root)
{
if (root == null)
return -1;
else
{
Node current = root;
while (current.Left!=null)
{
current = current.Left;
}
return current.Data;
}
}
public int FindMaxValue()
{
return FindMaxValue(_root);
}
private int FindMaxValue(Node root)
{
if (_root == null)
return -1;
else
{
Node current = root;
while (current.Right!=null)
{
current = current.Right;
}
return current.Data;
}
}