Skip to main content

Minimum element in BST

Problem​

Given the root of a Binary Search Tree. The task is to find the minimum valued element in this given BST.

Examples:​

Example 1:

Input:
5
/ \
4 6
/ \
3 7
/
1
Output: 1

Example 2:

Input:
9
\
10
\
11
Output: 9

Your task:​

The task is to complete the function minValue() which takes root as the argument and returns the minimum element of BST. If the tree is empty, there is no minimum element, so return -1 in that case.

  • Expected Time Complexity: OO(Height of the BST)
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

  • 0<=n<=1040<=n<=10^4

Solution​

Python​

def minValue(self, root):
current = root
while(current.left is not None):
current = current.left
return current.data

Java​

int minValue(Node root) {
Node current = root;
while (current.left != null) {
current = current.left;
}
return current.data;
}

C++​

int minValue(Node* root) {
Node* current = root;
while (current->left != nullptr) {
current = current->left;
}
return current->data;
}

C​

int minValue(struct Node *root) {
struct Node* current = root;
while (current->left != NULL) {
current = current->left;
}
return current->data;
}
  • Time Complexity: OO(Height of the BST)
  • Auxiliary Space: O(1)O(1)