Given an element x, task is to find the value of its immediate smaller element.
👁 Image
Example :
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.
Approach :
- 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 :
OutputImmediate smaller element of 30 is 25
Complexity Analysis:
- 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)