Kth largest element in an N-array Tree
Given an N-array Tree consisting of N nodes and an integer K, the task is to find the Kth largest element in the given N-ary Tree.
Input: K = 3
The 3rd largest element in the given N-array tree is 77.
Input: K = 4
Approach: The given problem can be solved by finding the largest element in the given range for K number of times and keep updating the end of the range to the largest element found so far. Follow the steps below to solve the problem:
- Initialize a variable say, largestELE as INT_MIN.
- Define a function, say largestEleUnderRange(root, data), and perform the following steps:
- Initialize a variable say, ans as INT_MAX to store the Kth largest element.
- Iterate over the range [0, K – 1] recursively call for the function largestEleUnderRange(root, ans) and update the value of ans as largestELe and largestELe as INT_MIN.
- After completing the above steps, print the value of ans as the resultant Kth maximum value.
Below is the implementation of the above approach.
Time Complexity: O(N*K)
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.