The minimum value in a BST is always found in the leftmost node, as the BST property ensures that smaller values are consistently placed on the left subtree. Thus, starting at the root and following the left child pointers until no further left child exists will yield the minimum value.
classSolution {
publicintfindMaximum(TreeNode root) {
if (root ==null) {
thrownew IllegalArgumentException("Tree is empty");
}
// Iterative traversal to the right-most node TreeNode current = root;
while (current.right!=null) {
current = current.right;
}
return current.val; // Maximum value is in the right-most node }
publicstaticvoidmain(String[] args) {
// Example: Create a BST and find the maximum value Solution solution =new Solution();
TreeNode root =new TreeNode(40);
root.left=new TreeNode(30);
root.right=new TreeNode(50);
root.right.left=new TreeNode(45);
root.right.right=new TreeNode(60);
int maxValue = solution.findMaximum(root);
System.out.println("Maximum value: "+ maxValue); // Output: 60 }
}
classSolution:
deffindMaximum(self, root):
ifnot root:
raiseValueError("Tree is empty")
# Iterative traversal to the right-most node current = root
while current.right:
current = current.right
return current.val # Maximum value is in the right-most node# Example: Create a BST and find the maximum valueif __name__ =="__main__":
solution = Solution()
# Example tree root = TreeNode(40)
root.left = TreeNode(30)
root.right = TreeNode(50)
root.right.left = TreeNode(45)
root.right.right = TreeNode(60)
max_value = solution.findMaximum(root)
print("Maximum value:", max_value) # Output: 60
⏰ 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).