Given an element x, task is to find the value of its immediate smaller element.
Input : x = 30 (for above tree) Output : Immediate smaller element is 25
Explanation : Elements 2, 15, 20 and 25 are smaller than x i.e, 30, but 25 is the immediate smaller element and hence the answer.
- Let res be the resultant node.
- Initialize the resultant Node as NULL.
- For every Node, check if data of root is greater than res, but less than x. if yes, update res.
- Recursively do the same for all nodes of the given Generic Tree.
- Return res, and res->key would be the immediate smaller element.
Below is the implementation of above approach :
Immediate smaller element of 30 is 25
Time Complexity : O(N), where N is the number of nodes in N-ary Tree.
Auxiliary Space : O(N), for recursive call(worst case when a node has N number of childs)
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.
- Find the nearest smaller numbers on left side in an array
- Median of two sorted arrays of different sizes | Set 1 (Linear)
- Count pairs in a binary tree whose sum is equal to a given value x
- Find the Missing Number in a sorted array
- First strictly smaller element in a sorted array in Java
- First strictly greater element in a sorted array in Java
- Next Smaller Element
- Longest subarray such that the difference of max and min is at-most one
- Josephus Problem | (Iterative Solution)
- Delete array element in given index range [L – R]