# Find pairs with given sum such that pair elements lie in different BSTs

Given two Binary Search Trees (BST) and a given sum. The task is to find pairs with given sum such that each pair elements must lie in different BST.

Examples:

```Input : sum = 10
8                    5
/   \                /   \
3     10             2    18
/  \      \         /   \
1    6      14      1     3
/ \     /              \
5   7   13              4
Output : (5,5), (6,4), (7,3), (8,2)
In above pairs first element lies in first
BST and second element lies in second BST
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

A simple solution for this problem is to store Inorder traversal of one tree in auxiliary array then pick element one by one from the array and find its pair in other tree for given sum. Time complexity for this approach will be O(n2) if total nodes in both the trees are equal.

An efficient solution for this solution is to store Inorder traversals of both BSTs in two different auxiliary arrays vect1[] and vect2[]. Now we follow method1 of this article. Since Inorder traversal of BST is always gives sorted sequence, we don not need to sort our arrays.

• Take iterator left and points it to the left corner vect1[].
• Take iterator right and points it to the right corner vect2[].
• Now if vect11[left] + vect2[right] < sum then move left iterator in vect1[] in forward direction i.e; left++.
• Now if vect1[left] + vect2[right] > sum then move right iterator in vect[] in backward direction i.e; right–.

Below is implementation of above idea.

```// C++ program to find pairs with given sum such
// that one element of pair exists in one BST and
// other in other BST.
#include<bits/stdc++.h>
using namespace std;

// A binary Tree node
struct Node
{
int data;
struct Node *left, *right;
};

// A utility function to create a new BST node
// with key as given num
struct Node* newNode(int num)
{
struct Node* temp = new Node;
temp->data = num;
temp->left = temp->right = NULL;
return temp;
}

// A utility function to insert a given key to BST
Node* insert(Node* root, int key)
{
if (root == NULL)
return newNode(key);
if (root->data > key)
root->left = insert(root->left, key);
else
root->right = insert(root->right, key);
return root;
}

// store storeInorder traversal in auxiliary array
void storeInorder(Node *ptr, vector<int> &vect)
{
if (ptr==NULL)
return;
storeInorder(ptr->left, vect);
vect.push_back(ptr->data);
storeInorder(ptr->right, vect);
}

// Function to find pair for given sum in different bst
// vect1[]  --> stores storeInorder traversal of first bst
// vect2[]  --> stores storeInorder traversal of second bst
void pairSumUtil(vector<int> &vect1, vector<int> &vect2,
int sum)
{
// Initialize two indexes to two different corners
// of two vectors.
int left = 0;
int right = vect2.size() - 1;

// find pair by moving two corners.
while (left < vect1.size() && right >= 0)
{
// If we found a pair
if (vect1[left] + vect2[right] == sum)
{
cout << "(" << vect1[left] << ", "
<< vect2[right] << "), ";
left++;
right--;
}

// If sum is more, move to higher value in
// first vector.
else if (vect1[left] + vect2[right] < sum)
left++;

// If sum is less, move to lower value in
// second vector.
else
right--;
}
}

// Prints all pairs with given "sum" such that one
// element of pair is in tree with root1 and other
// node is in tree with root2.
void pairSum(Node *root1, Node *root2, int sum)
{
// Store inorder traversals of two BSTs in two
// vectors.
vector<int> vect1, vect2;
storeInorder(root1, vect1);
storeInorder(root2, vect2);

// Now the problem reduces to finding a pair
// with given sum such that one element is in
// vect1 and other is in vect2.
pairSumUtil(vect1, vect2, sum);
}

// Driver program to run the case
int main()
{
// first BST
struct Node* root1 = NULL;
root1 = insert(root1, 8);
root1 = insert(root1, 10);
root1 = insert(root1, 3);
root1 = insert(root1, 6);
root1 = insert(root1, 1);
root1 = insert(root1, 5);
root1 = insert(root1, 7);
root1 = insert(root1, 14);
root1 = insert(root1, 13);

// second BST
struct Node* root2 = NULL;
root2 = insert(root2, 5);
root2 = insert(root2, 18);
root2 = insert(root2, 2);
root2 = insert(root2, 1);
root2 = insert(root2, 3);
root2 = insert(root2, 4);

int sum = 10;
pairSum(root1, root2, sum);

return 0;
}
```

Output:

```(5,5),(6,4),(7,3),(8,2)
```

Time complexity : O(n)
Auxiliary space : O(n)

We have another space optimized approach to solve this problem. The idea is to convert bst into doubly linked list and apply above method for doubly linked list.See this article.

Time complexity : O(n)
Auxiliary Space : O(1)

This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

# GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
2.5 Average Difficulty : 2.5/5.0
Based on 11 vote(s)