VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-median-in-bst-subtree-from-kth-smallest-node/

⇱ Find Median in BST Subtree from Kth Smallest Node - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Median in BST Subtree from Kth Smallest Node

Last Updated : 23 Jul, 2025

Given a binary search tree, the task is to find the median of the subtree rooted with Kth smallest node of the tree.

Examples:

Input: N = 12, K = 9

50
/ \
25 75
/ \ \
15 45 90
/ \ / \ / \
11 20 30 49 80 100

Output: 85
Explanation: K=9. So the 9th smallest number is 75. The values of this subtree are 75 80 90 100. Now, the median of this is (80+90)/2 = 85

Approach: This can be solved with the following idea:

As it is BST, Inorder traversal of tree will give us sorted array. From there we can get the Kth smallest node. After that, iterate for that particular node and get the median.

Below are the steps involved:

  • Intialize a nodes of vector v.
  • Traverse in inorder, So as to get sorted vector.
  • Get the Kth smallest node.
  • Again Iterate in inorder traversal for kth samllest node and store them in another vector.
  • Once done, check the size of vector:
    • If even, median will be sum of both mid divide by 2.
    • If odd, median will be mid of vector.

Below is the implementation of the code:



Output
1

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment