Node with minimum value in a Binary Search Tree

Given a Binary Search Tree (BST), Where will you find the node containing the minimum value in the Tree?

For example: If the tree is as given below

Then the Minimum Value is 1. Write a function that returns the least value in a given BST.

Solution:

The minimum value in a Binary search tree is always in the left-most child node. (The maximum value will be in the right-most child node. If the left subtree is empty, then root stores the minimum value.

int getMinimum(Node* root)
{
    while(root->left != NULL)
        root = root->left;
    return root->data;
}
In this case, we are assuming the Node of the tree is defined as below:
struct Node
{
    Node* left;  // Left Subtree
    int data;
    Node * right; // Right Subtree
};

Note that the left-most node of the entire tree may be different (For example, the node with minimum vertical level may belong to the right sub-tree of the root) 

Feel free to provide your feedback / comments.  

0 Comments

Leave a comment