Find median of BST
Given a Binary Search Tree, find the median of it.
- If number of nodes are even: then median = ((n/2th node + ((n)/2th+1) node) /2
- If number of nodes are odd: then median = (n+1)/2th node.
Output: median of Below BST is 6.
Explanation: Inorder of Given BST will be
1, 3, 4, 6, 7, 8, 9 So, here median will 6.
Output: median of Below BST is 12
Median Of BST using Morris Inorder Traversal:
The idea is based on K’th smallest element in BST using O(1) Extra Space.
The task is very simple if we are allowed to use extra space but Inorder to traversal using recursion and stack both use Space which is not allowed here. So, the solution is to do Morris Inorder traversal as it doesn’t require extra space.
Follow the steps mentioned below to implement the idea:
- Count the number of nodes in the given BST using Morris Inorder Traversal.
- Then perform Morris Inorder traversal one more time by counting nodes and by checking if the count is equal to the median point.
- To consider even no. of nodes, an extra pointer pointing to the previous node is used.
Below is the implementation of the above approach:
Median of BST is 50
Time Complexity: O(N)
Auxiliary Space: O(1)
My Personal Notes arrow_drop_up
Please Login to comment...