Find all the pairs with given sum in a BST | Set 2
Input: 2 / \ 1 6 / \ 5 7 / 3 \ 4 sum = 8 Output: 1 7 2 6 3 5 Input: 2 / \ 1 3 \ 4 sum = 5 Output: 1 4 2 3
Approach: Traverse the tree in a pre-order manner from both the side, left and right, and store the values of the left and right sides into the ArrayList LeftList and RightList respectively. On reaching the leaf node, take out the left side last value and a right side last value from the respective ArrayLists. There will be three conditions:
- left side value + right side value < sum: Delete the last value of LeftList and make the left side execution to the right side because on moving from the left side to the right side in the tree the value of node increases.
- left side value + right side value > sum: Delete the last value of RightList and make the right side execution to the left side because on moving from the right side to the left side in the tree the value of node decreases.
- left side value + right side value = sum: Delete the last value of both the lists and make the left side execution to the right side and right side execution to the left side.
Below is the implementation of the above approach:
1 7 2 6 3 5
Approach 2 using stack:
Given A BST print all the pairs with target sum present in BST. BST not contains any duplicate.
GIVEN ABOVE BST:
Input : sum = 10 Output: 0 10 1 9 2 8 3 7 4 6
Input: sum = 9 Output: 0 9 1 8 2 7 3 6 4 5
Approach discussed below is similar to find pair in sorted array using two pointer technique.
The idea used here is same as the two pointer algorithm for find pair with target sum in O(n) time
1. Create Two stacks
i) for inorder.
ii) for reverse Inorder.
2. Now populating one by one from each stack
i) if sum == k we add to the sum and make find1 and find2 to false to get new elements
ii) if sum < k we add to the sum and make find1 to false.
iii) if sum == k we add to the sum and make find2 to false.
4. Breaking condition when curr1->data > curr2->data.
Below is the implementation.
0 10 1 9 2 8 3 7 4 6
Time Complexity: O(N)
Auxiliary Space: O(N)