29. Median of BST
The problem can be found at the following link: Question Link
My Approach
LOL GFG made this question appear easy, but it is not that easy. Although the task itself seems straightforward – perform Inorder traversal to get a vector of elements and then find the median from that vector – the real challenge lies in achieving it with limited auxiliary space. We need to ensure the solution uses only O(h)
auxiliary space (where h is the height of the tree), not O(n)
(where n is the number of all nodes). So let's figure out the solution within the constraints.
To find the median of a Binary Search Tree (BST)
First, we calculate the total number of nodes in the BST using the
totalNodes
function, which is a simple recursive function that counts the number of nodes in the left subtree, right subtree, and the current node.Next, we perform the modified inorder traversal using the
modifiedInorder
function. This function maintains aprev
pointer to keep track of the previously visited node, ani
variable to keep track of the current node's position, and anout
variable to store the median.During the inorder traversal, when we reach the
mid
position (the middle element for odd-sized trees or the left-middle element for even-sized trees), we calculate the median accordingly. If the total number of nodes isodd
, the median is the value of the node at the mid position. Otherwise, for even-sized trees, the median can be found by taking the average of the values stored in the nodes at positionsmid
andmid-1
. These positions refer to the currentroot
node and theprev
node, respectively.
Time and Auxiliary Space Complexity
Time Complexity: The time complexity of the
totalNodes
function is O(N), whereN
is the number of nodes in the BST. ThemodifiedInorder
function takesO(N)
time since we visit each node once. Therefore, the overall time complexity of thefindMedian
function isO(N)
.Auxiliary Space Complexity:
O(H)
, whereH
is the height of the BST. This is because themodifiedInorder
function uses recursive calls, and the maximum height of the function call stack is equal to the height of the BST.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated