Given a Binary Search Tree (BST), find the minimum value stored in the tree. In a BST, the left child of a node contains a value less than the node itself, and the right child contains a value greater. You need to return the smallest value among all the nodes. If the tree is empty, return null
or an appropriate error/indicator.
Find the Minimum Value in a BST - Algorithm, Visualization, Examples
Visualization Player
Problem Statement
Examples
Solution
Algorithm Steps
Code
C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = node->right = NULL;
return node;
}
int findMin(TreeNode* root) {
if (root == NULL) {
printf("Tree is empty\n");
exit(1);
}
while (root->left != NULL) {
root = root->left;
}
return root->val;
}
int main() {
TreeNode* root = createNode(5);
root->left = createNode(3);
root->right = createNode(7);
root->left->left = createNode(2);
root->left->right = createNode(4);
root->right->left = createNode(6);
root->right->right = createNode(8);
printf("%d\n", findMin(root));
return 0;
}
Comments
Loading comments...