VOOZH about

URL: https://www.geeksforgeeks.org/dsa/kth-smallest-element-in-an-n-ary-tree/

⇱ Kth Smallest Element in an N-ary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Kth Smallest Element in an N-ary Tree

Last Updated : 23 Jul, 2025

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:
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:

  • Initialize a global variable, say MinimumElement as INT_MAX.
  • Declare a function smallestEleUnderRange(root, data) and perform he following operations: 
    • If root.data is more than data, then update MinimumElement as min of MinimumElement and root.data.
    • Iterate over all children of the root. Call recursive function smallestEleUnderRange(child, data).
  • 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.

 
 


Output: 
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.


 

Comment
Article Tags:
Article Tags: