How to find minimum value in a Binary Search Tree (BST)
The naive approach
, visit all nodes, and compare a value in each node. A better approach is to use the definition of a binary search tree
.
A Binary Search Tree
(BST) is a binary tree where each node has a key and meet the following requirements:
- The
left subtree
of a node contains nodes with keyssmaller
then the node's key - The
right subtree
of a node contains nodes with keyslarger
then the node's key - The
left
andright
subtrees arebinary search trees
In other words, the most leftist node in a BST has a minimum value.
Examples
Let's see a couple of BST
examples. As we see the leftmost node
has a minimum value and the leftmost node it's a left node without
a left child.
In this example, the root node
has the minimum
value.
Algorithm
The answer to the question "How to find minimum value in a Binary Search Tree (BST)":
- always
go
to theleft
until finding a node without aleft child
. This node will haveminimum
value in aBST
.
The last question we need to answer before start writing code. What should the algorithm do if a BST
is empty? For simplicity, let's return -1
if a BST
is empty.
Note: ask a question on your interview. Is it ok to return a
-1
ifBST
is empty?BST
can store not only positive but negative values as well.
public int MinValue(TreeNode root)
{
if (root == null)
{
return -1;
}
TreeNode node = root;
while (node.Left != null)
{
node = node.Left;
}
return node.Value;
}