![]() |
VOOZH | about |
Given an N-array Tree (Generic Tree) and an integer K, the task is to find the Kth smallest element in an N-array Tree.
Examples:
Input: 10
/ / \ \
2 34 56 100
/ \ | / | \
77 88 1 7 8 9
K = 3
Output: 7
Explanation: 7 is the 3rd smallest element in the tree. The first two smallest elements are 1 and 2 respectively.Input: 1
/ \ \
2 3 4
/ \
5 6
K = 4
Output: 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:
Below is the implementation of the above approach.
7
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.