Finding Min and Max nodes
What you'll learn: How to exploit the sorted structure of a Binary Search Tree to instantly locate the smallest and largest values.
The "Left-Heavy" and "Right-Heavy" Rule
In a Binary Search Tree (BST), every node follows a strict ordering rule: smaller values go to the left, and larger values go to the right. Because of this consistent organization, finding the minimum or maximum value doesn't require searching the whole tree. You just need to pick a direction and keep going until you hit a dead end.
Think of a BST like a family tree organized by height. If the shortest people always stand to the left of their parents and the tallest always stand to the right, finding the shortest person in the entire family is easy: just keep moving left.
Finding the Minimum
To find the minimum value, start at the Root. Look at the left child. If it exists, move there. Repeat this process until you reach a node that has no left child (NULL). That final node is your minimum. Even if that node has children on its right, those right-side children are guaranteed to be larger than the node itself.
Finding the Maximum
Finding the maximum is the exact mirror image. Start at the Root and keep moving to the right child until you can’t go any further. The rightmost leaf (or node without a right child) is your maximum.
Implementation in C
We use a simple while loop to "drill down" into the tree. We don't need recursion here, though you could use it; a loop is more memory-efficient for this specific task.
struct Node {
int data;
struct Node *left;
struct Node *right;
};
// Function to find the minimum value node
struct Node* findMin(struct Node* root) {
if (root == NULL) return NULL; // Tree is empty
struct Node* current = root;
// Keep sliding to the left
while (current->left != NULL) {
current = current->left;
}
return current;
}
// Function to find the maximum value node
struct Node* findMax(struct Node* root) {
if (root == NULL) return NULL; // Tree is empty
struct Node* current = root;
// Keep sliding to the right
while (current->right != NULL) {
current = current->right;
}
return current;
}
Key takeaway
In a BST, the minimum value is the leftmost node, and the maximum value is the rightmost node.