I need to find the kth smallest element in the binary search tree without using any static/global variable. How to achieve it efficiently?
The solution that I have in my mind is doing the operation in O(n), the worst case since I am planning to do an inorder traversal of the entire tree. But deep down I feel that I am not using the BST property here. Is my assumptive solution correct or is there a better one available ?
I need to find the kth smallest element in the binary search tree without
Share
Here’s just an outline of the idea:
In a BST, the left subtree of node
Tcontains only elements smaller than the value stored inT. Ifkis smaller than the number of elements in the left subtree, thekth smallest element must belong to the left subtree. Otherwise, ifkis larger, then thekth 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:
T.kth smallest. So, we reduce the problem to finding thek - num_elements(left subtree of T)smallest element of the right subtree.kth smallest is somewhere in the left subtree, so we reduce the problem to finding thekth smallest element in the left subtree.Complexity analysis:
This takes
O(depth of node)time, which isO(log n)in the worst case on a balanced BST, orO(log n)on average for a random BST.A BST requires
O(n)storage, and it takes anotherO(n)to store the information about the number of elements. All BST operations takeO(depth of node)time, and it takesO(depth of node)extra time to maintain the “number of elements” information for insertion, deletion or rotation of nodes. Therefore, storing information about the number of elements in the left subtree keeps the space and time complexity of a BST.