Given a Binary Search Tree and a SUM. The task is to check if there exists any triplet(group of 3 elements) in the given BST with the given SUM.
Input : SUM = 21 Output : YES There exists a triplet (7, 3, 11) in the above given BST with sum 21. Input : SUM = 101 Output : NO
It is known that elements in the inorder traversal of BST are sorted in increasing order. So, the idea is to do inorder traversal on the given BST and store the elements in a vector or array. Now the task reduces to check for a triplet with given sum in a sorted array.
Now to do this, start traversing the array and for every element A[i] check for a pair with sum (SUM – A[i]) in the remaining sorted array.
To do this: 1) Initialize two index variables to find the candidate elements in the sorted array. (a) Initialize first to the leftmost index: l = 0 (b) Initialize second the rightmost index: r = ar_size-1 2) Loop while l < r. (a) If (A[l] + A[r] == sum) then return 1 (b) Else if( A[l] + A[r] < sum ) then l++ (c) Else r-- 3) If no such candidates are found in the whole array, return 0
Below is the implementation of the above approach:
Time Complexity: O(N2)
Auxiliary Space: O(N), where N is the number of nodes in the given BST.
- Check if given sorted sub-sequence exists in binary search tree
- Triplet with a given sum in BST | Set 2
- Find a triplet that sum to a given value
- Find a triplet such that sum of two equals to third element
- Find if there is a triplet in a Balanced BST that adds to zero
- Find a triplet in an array whose sum is closest to a given number
- Minimum number of moves after which there exists a 3X3 coloured square
- Check whether BST contains Dead End or not
- Check if a given graph is Bipartite using DFS
- Check if two trees are Mirror | Set 2
- Check if two BSTs contain same set of elements
- Check if two expressions with brackets are same
- Check if two given key sequences construct same BSTs
- A program to check if a binary tree is BST or not
- Check if each internal node of a BST has exactly one child
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.