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.
Input: N = 5 8 / \ 7 10 / / \ 2 9 13 Output: 7 As 7 is the smallest number in BST which is greater than N = 5. Input: N = 10 8 / \ 5 11 / \ 2 7 \ 3 Output: 11 As 11 is the smallest number in BST which is greater than N = 10.
A recursive solution for this problem has been already been discussed in this post. Below is an iterative approach for the problem:
Using Morris Traversal the above problem can be solved in constant space. Find the inorder successor of the target. Keep two pointers, one pointing to the current node and one for storing the answer.
Below is the implementation of the above approach:
Time complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Smallest number in BST which is greater than or equal to N
- Largest number in BST which is less than or equal to N
- Count pairs in BST with sum greater than K
- Check for Symmetric Binary Tree (Iterative Approach)
- Get level of a node in binary tree | iterative approach
- Deepest left leaf node in a binary tree | iterative approach
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Deepest right leaf node in a binary tree | Iterative approach
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Construct Binary Tree from given Parent Array representation | Iterative Approach
- Iterative approach to check if a Binary Tree is Perfect
- Iterative approach to check for children sum property in a Binary Tree
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Iterative Approach to check if two Binary Trees are Isomorphic or not
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Print all nodes at distance K from given node: Iterative Approach
- K'th Largest Element in BST when modification to BST is not allowed
- Convert a normal BST to Balanced BST
- Check if a Binary Tree is BST : Simple and Efficient Approach
- Queries to count array elements greater than or equal to a given number with updates
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.