In: Computer Science
in C++, given a binary search tree of ints, in which each node contains a size parameter (also an int), explain, in English, not code, how you would find the median element of the tree in theta(log N) time.
`Hey,
Note: Brother if you have any queries related the answer please do comment. I would be very happy to resolve all your queries.
We can find kth element in BST where k=n/2 for median
Here's just an outline of the idea:
In a BST, the left subtree of node T contains only elements smaller than the value stored in T. If k is smaller than the number of elements in the left subtree, the kth smallest element must belong to the left subtree. Otherwise, if k is larger, then the kth smallest element is in the right subtree.
We can augment the BST to have each node in it store the number of elements in its left subtree (assume that the left subtree of a given node includes that node). With this piece of information, it is simple to traverse the tree by repeatedly asking for the number of elements in the left subtree, to decide whether to do recurse into the left or right subtree.
Now, suppose we are at node T:
The abovee algorithm requires O(log(n))
Kindly revert for any queries
Thanks.