classSolution {
// Method to find the minimum value in the BSTpublicintfindMin(TreeNode root) {
if (root ==null) {
thrownew IllegalArgumentException("Tree must contain at least one node.");
}
TreeNode current = root;
while (current.left!=null) {
current = current.left; // Traverse left until no left child exists }
return current.val; // Return the value of the leftmost node }
// Example usagepublicstaticvoidmain(String[] args) {
Solution solution =new Solution();
// Example Input: Constructing the BST TreeNode root =new TreeNode(10);
root.left=new TreeNode(5);
root.right=new TreeNode(15);
root.left.left=new TreeNode(2);
root.left.right=new TreeNode(7);
// Output: Find minimum value System.out.println("Minimum value in BST: "+ solution.findMin(root)); // Output: 2 }
}
classSolution:
deffindMin(self, root):
ifnot root:
raiseValueError("Tree must contain at least one node.")
current = root
while current.left:
current = current.left # Traverse left until no left child existsreturn current.val # Return the value of the leftmost node# Example usageif __name__ =="__main__":
solution = Solution()
# Example Input: Constructing the BST root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
root.left.left = TreeNode(2)
root.left.right = TreeNode(7)
# Output: Find minimum value print("Minimum value in BST:", solution.findMin(root)) # Output: 2
⏰ Time complexity: O(h), where h is the height of the tree. For a balanced tree, the height is approximately O(log n), where n is the number of nodes. In the worst case (completely unbalanced), the height is O(n).