K’th Largest Element in BST when modification to BST is not allowed
- Difficulty Level : Easy
- Last Updated : 15 Jul, 2022
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.
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(n).
In worst case the code can traverse each and every node of the tree if the k given is equal to n (total number of nodes in the tree). Therefore overall time complexity is O(n).
- 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