Given the root of a Binary Search Tree, find the median of it.
Let the nodes of the BST, when written in ascending order (inorder traversal), be represented as V1, V2, V3, …, Vn, where n is the total number of nodes in the BST.
Output: 12 Explanation: The inorder of given BST is 4, 8, 10, 12, 14, 20, 22. Here, n = 7, so, here median will be ((7+1)/2)th value, i.e., 4th value, i.e, 12.
[Approach 1] Median Of BST using Inorder Traversal - O(n) Time and O(n) Space
The idea is based on the property of BST, i.e., inorder traversal of BST gives a sorted list. We will store the inorder traversal of the BST and return the median.
Output
12
[Approach 2] Median Of BST using Morris Inorder Traversal - O(n) Time and O(1) Space
The idea is to perform an inorder traversal of the given Binary Search Tree using the Morris Traversal algorithm.
During the first traversal, we count the total number of nodes in the BST. Then, during the second traversal, we again perform Morris traversal while maintaining a counter for visited nodes. Once the counter reaches the middle position (depending on whether the number of nodes is odd or even), we return the value of the current node as the median.