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
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.