Given a Binary Search Tree, find median of it.
If no. of nodes are even: then median = ((n/2th node + (n+1)/2th node) /2
If no. of nodes are odd : then median = (n+1)/2th node.
Given BST(with odd no. of nodes) is : 6 / \ 3 8 / \ / \ 1 4 7 9 Inorder of Given BST will be : 1, 3, 4, 6, 7, 8, 9 So, here median will 6. Given BST(with even no. of nodes) is : 6 / \ 3 8 / \ / 1 4 7 Inorder of Given BST will be : 1, 3, 4, 6, 7, 8 So, here median will (4+6)/2 = 5.
Asked in : Google
To find the median, we need to find the Inorder of the BST because its Inorder will be in sorted order and then find the median i.e.
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 traversal using recursion and stack both uses Space which is not allowed here. So, the solution is to do Morris Inorder traversal as it doesn’t require any extra space.
Implementation: 1- Count the no. of nodes in the given BST using Morris Inorder Traversal. 2- Then Perform Morris Inorder traversal one more time by counting nodes and by checking if count is equal to the median point. To consider even no. of nodes an extra pointer pointing to the previous node is used.
Median of BST is 50
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find duplicates in O(n) time and O(1) extra space | Set 1
- Find the maximum repeating number in O(n) time and O(1) extra space
- Rearrange positive and negative numbers in O(n) time and O(1) extra space
- Design a stack that supports getMin() in O(1) time and O(1) extra space
- Find median in row wise sorted matrix
- Find last two remaining elements after removing median of any 3 consecutive elements repeatedly
- Find the closest element in Binary Search Tree | Space Efficient Method
- Find a sorted subsequence of size 3 in linear time
- Geometric Median
- Mean and Median of a matrix
- Median after K additional integers
- Maximize the median of an array
- Median of sliding window in an array
- Median of two sorted arrays of same size