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?
- 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(1).
As no extra space is needed.
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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find k-th smallest element in BST (Order Statistics in BST)
- Largest element smaller than current element on left for every element in Array
- Second largest element in BST
- K'th Largest element in BST using constant extra space
- Maximum sum from a tree with adjacent levels not allowed
- Two nodes of a BST are swapped, correct the BST
- Convert a normal BST to Balanced BST
- Two nodes of a BST are swapped, correct the BST | Set-2
- Find the largest BST subtree in a given Binary Tree | Set 1
- Largest BST in a Binary Tree | Set 2
- Largest number in BST which is less than or equal to N
- Largest number less than or equal to N in BST (Iterative Approach)
- Sum of k largest elements in BST
- A program to check if a binary tree is BST or not
- Check whether BST contains Dead End or not
- Check if a Binary Tree (not BST) has duplicate values
- Check given array of size n can represent BST of n levels or not
- K'th smallest element in BST using O(1) Extra Space
- Maximum element between two nodes of BST
- Unbounded Knapsack (Repetition of items allowed)