Maximum in a Binary Search Tree
EasyUpdated: Aug 2, 2025
Problem
Given a non-empty binary search tree (BST), write a function to find and return the minimum data value found in the tree.
Examples
Example 1
Input:
10
/ \
5 15
/ \
2 7
Output:
2
Explanation:
The smallest value in the tree is found in the leftmost node, which is 2.
Example 2
Input:
20
/
15
/
10
Output:
10
Explanation:
The minimum value is located in the leftmost node in the tree, which is 10.
Similar Problem
[Minimum in a Binary Tree](minimum-in-a-binary-tree) [Maximum in a Binary Tree](maximum-in-a-binary-tree) [Minimum in a Binary Search Tree](minimum-in-a-binary-search-tree)
Solution
Method 1 - Using BST Properties
In a Binary Search Tree, the largest value will always be in the rightmost leaf node, since values increase as you traverse to the right.
Approach
- Start at the root node.
- Traverse the tree iteratively (or recursively), moving to the right child as long as it exists.
- When you reach a node with no right child, that node contains the maximum value.
Code
Java
class Solution {
// Method to find the minimum value in the BST
public int findMin(TreeNode root) {
if (root == null) {
throw new 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 usage
public static void main(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
}
}
Python
class Solution:
def findMin(self, root):
if not root:
raise ValueError("Tree must contain at least one node.")
current = root
while current.left:
current = current.left # Traverse left until no left child exists
return current.val # Return the value of the leftmost node
# Example usage
if __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
Complexity
- ⏰ Time complexity:
O(h), wherehis the height of the tree. For a balanced tree, the height is approximatelyO(log n), wherenis the number of nodes. In the worst case (completely unbalanced), the height isO(n). - 🧺 Space complexity:
O(1)