K’th Largest Element in BST when modification to BST is not allowed
Given a Binary Search Tree (BST) and a positive integer k, find the k’th largest element in the Binary Search Tree.
For example, in the following BST, if k = 3, then output should be 14, and if k = 5, then output should be 10.
Become a success story instead of just reading about them. Prepare for coding interviews at Amazon and other top product-based companies with our Amazon Test Series. Includes topic-wise practice questions on all important DSA topics along with 10 practice contests of 2 hours each. Designed by industry experts that will surely help you practice and sharpen your programming skills. Wait no more, start your preparation today!
We have discussed two methods in this post. The method 1 requires O(n) time. The method 2 takes O(h) time where h is height of BST, but requires augmenting the BST (storing count of nodes in left subtree with every node).
Can we find k’th largest element in better than O(n) time and no augmentation?
- The idea is to do reverse inorder traversal of BST. Keep a count of nodes visited.
- The reverse inorder traversal traverses all nodes in decreasing order, i.e, visit the right node then centre then left and continue traversing the nodes recursively.
- While doing the traversal, keep track of the count of nodes visited so far.
- When the count becomes equal to k, stop the traversal and print the key.
K'th largest element is 80 K'th largest element is 70 K'th largest element is 60 K'th largest element is 50 K'th largest element is 40 K'th largest element is 30 K'th largest element is 20
- Time Complexity: O(h + k).
The code first traverses down to the rightmost node which takes O(h) time, then traverses k elements in O(k) time. Therefore overall time complexity is O(h + k).
- Auxiliary Space: O(h).
Max recursion stack of height h at a given time.
This article is contributed by Chirag Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above