Lesson 11 of 14
Min and Max
Finding Min and Max in a BST
The BST property tells you exactly where the minimum and maximum values live:
- Minimum: always in the leftmost node — keep going left until there's no left child.
- Maximum: always in the rightmost node — keep going right until there's no right child.
5
/ \
3 7
/ \ / \
1 4 6 8
Min = 1 (leftmost), Max = 8 (rightmost).
Implementation
int bst_min(struct Node *root) {
if (root->left == NULL) return root->val;
return bst_min(root->left);
}
int bst_max(struct Node *root) {
if (root->right == NULL) return root->val;
return bst_max(root->right);
}
No comparison needed — the BST structure guarantees the position of the extremes.
Your Task
Implement int bst_min(struct Node *root) and int bst_max(struct Node *root). Assume the tree is non-empty.
TCC compiler loading...
Loading...
Click "Run" to execute your code.