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.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Level Order Tree Traversal
- Floor and Ceil from a BST
- Print BST keys in given Range | O(1) Space
- Root to leaf path sum equal to a given number in BST
- Total sum except adjacent of a given node in BST
- Number of elements smaller than root using preorder traversal of a BST
- Reallocation of elements based on Locality of Reference
- Subarray whose sum is closest to K
- Next Greater Element | Set-2
- Floor in Binary Search Tree (BST)