Given a Binary Search Tree (BST) and a positive integer k, find the k’th largest element in the Binary Search Tree.
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?
In this post, a method is discussed that takes O(h + k) time. This method doesn’t require any change to BST.
The idea is to do reverse inorder traversal of BST. The reverse inorder traversal traverses all nodes in decreasing order. While doing the traversal, we keep track of count of nodes visited so far. When the count becomes equal to k, we 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: 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).
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
- Largest number with one swap allowed
- Find the largest rectangle of 1's with swapping of columns allowed
- Find n-th element in a series with only 2 digits (4 and 7) allowed
- Sort an array with swapping only with a special element is allowed
- Find n-th element in a series with only 2 digits (4 and 7) allowed | Set 2 (log(n) method)
- Second largest element in BST
- K'th largest element in a stream
- K’th Smallest/Largest Element using STL
- Second Largest element in n-ary tree
- Find Second largest element in an array
- Largest element in the array that is repeated exactly k times
- Find the Second Largest Element in a Linked List
- Program to find largest element in an array
- C Program to find largest element in an array
- K'th Smallest/Largest Element in Unsorted Array | Set 1