Kth Smallest Element in an N-ary Tree
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
/ / \ \
2 34 56 100
/ \ | / | \
77 88 1 7 8 9
K = 3
Explanation: 7 is the 3rd smallest element in the tree. The first two smallest elements are 1 and 2 respectively.
/ \ \
2 3 4
K = 4
Approach: The problem can be solved by finding the smallest element in the given range K-times and keep updating the upper end of the range to the smallest element found so far. Follow the steps below to solve the problem:
- Initialize a global variable, say MinimumElement as INT_MAX.
- Declare a function smallestEleUnderRange(root, data) and perform he following operations:
- Declare a function KthSmallestElement(root, k) to perform the following operations:
- Initialize a variable, say ans as INT_MIN, to store the Kth smallest element.
- Iterate over the range [0, K – 1] using a variable i and perform the following:
- Call smallestEleUnderRange(root, ans) function and then update ans as MinimumElement and then MinimumElement as INT_MAX.
- Finally, print ans as the required answer.
Below is the implementation of the above approach.
Time Complexity: O(N * K) where N is the number of nodes in the given tree.
Auxiliary Space: O(1), but the recursion stack uses a maximum of O(N) space.