Minimum and Maximum in BST

You are given the root of a Binary Search Tree (BST) containing integer values.

Your task is to find the minimum and maximum values present in the BST.

In a Binary Search Tree:

  • All values in the left subtree of a node are smaller than the node's value.
  • All values in the right subtree of a node are greater than the node's value.

Return the minimum and maximum values present in the BST, as a 2-element array/list, where the first element is the minimum value and the second element is the maximum value:

Example 1:

Input: root = [8, 3, 12, 1, 6, 10, 14]

Output: [1, 14]

Explanation:The smallest value in the BST is 1, and the largest value is 14. Therefore, the answer is [1, 14].

Example 2:

Input: root = [20, 10, 30, 5, 15, 25, 40, null, 7]

Output: [5, 40]

Explanation: Following the leftmost path gives the minimum value 5, while following the rightmost path gives the maximum value 40. Therefore, the answer is [5, 40].

Now Your Turn!

Pick the correct output for the given input

Input: root = [15, 8, 22, 4, 11, 18, 27, null, 6]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= number of nodes <= 105
  • -109 <= Node.val <= 109
  • All node values are unique.
  • The given tree is a valid Binary Search Tree.
0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode* left;
* TreeNode* right;
* };
*/
 
class Solution {
public:
vector<int> findMinMax(TreeNode* root) {
// Your code goes here
}
};
Test Case

Input:

Root