![]() |
VOOZH | about |
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 100Output: 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:
Below is the implementation of the code:
1
Time Complexity: O(N)
Auxiliary Space: O(N)