由于BST的属性,所以查找最大与最小值的代码几乎是微不足道的事情。人们总可以在根节点左子树的最左侧的节点上找到BST内的最小值,另一方面,则会在跟节点有字数的最右侧节点上找到BST内的最大值。
public int FindMin()
{
Node current = root;
while (!(current.Left == null))
{
current = current.Left;
}
return current.Data;
}
public int FindMax()
{
Node current = root;
while (!(current.Right == null))
{
current = current.Right;
}
return current.Data;
}
public Node Find(int key)
{
Node current = root;
while (current.Data != key)
{
if (key < current.Data)
{
current = current.Left;
}
else
{
current = current.Right;
}
if (current == null)
{
return null;
}
}
return current;
}