Given a BST, the task is to find the sum of all elements greater than and equal to kth largest element.
Input : K = 3 8 / \ 7 10 / / \ 2 9 13 Output : 32 Explanation: 3rd largest element is 9 so sum of all elements greater than or equal to 9 are 9 + 10 + 13 = 32. Input : K = 2 8 / \ 5 11 / \ 2 7 \ 3 Output : 19 Explanation: 2nd largest element is 8 so sum of all elements greater than or equal to 8 are 8 + 11 = 19.
The idea is to traverse BST in Inorder traversal in a reverse way (Right Root Left).
Note that Inorder traversal of BST accesses elements in a sorted (or increasing) order, hence the reverse of inorder traversal will be in a sorted order(decreasing). While traversing, keep track of the count of visited Nodes and keep adding Nodes until the count becomes k.
- Second largest element in BST
- Largest number in BST which is less than or equal to N
- Largest BST in a Binary Tree | Set 2
- Second Largest element in n-ary tree
- Largest sub-tree having equal no of 1's and 0's
- Largest Independent Set Problem | DP-26
- K'th largest element in a stream
- Largest value in each level of Binary Tree
- K'th Largest Element in BST when modification to BST is not allowed
- Find largest subtree sum in a tree
- K'th Largest element in BST using constant extra space
- Largest number less than or equal to N in BST (Iterative Approach)
- Range query for Largest Sum Contiguous Subarray
- Find the largest BST subtree in a given Binary Tree | Set 1
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.