Given a Binary Search Tree and a number N, the task is to find the smallest number in the binary search tree that is greater than or equal to N. Print the value of the element if it exists otherwise print -1.
Input: N = 20
Explanation: 21 is the smallest element greater than 20.
Input: N = 18
Explanation: 19 is the smallest element greater than 18.
The idea is to follow the recursive approach for solving the problem i.e. start searching for the element from the root.
- If there is a leaf node having a value less than N, then element doesn’t exist and return -1.
- Otherwise, if node’s value is greater than or equal to N and left child is NULL or less than N then return the node value.
- Else if node’s value is less than N, then search for the element in the right subtree.
- Else search for the element in the left subtree by calling the function recursively according to the left or right value.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Total number of possible Binary Search Trees and Binary Trees with n keys
- Binary Search Tree | Set 1 (Search and Insertion)
- Binary Search Tree | Set 2 (Delete)
- Check if two nodes are cousins in a Binary Tree | Set-2
- Root to leaf path sum equal to a given number in BST
- Total sum except adjacent of a given node in BST
- Number of elements smaller than root using preorder traversal of a BST
- Reallocation of elements based on Locality of Reference
- Subarray whose sum is closest to K
- Next Greater Element | Set-2