Print all pairs from two BSTs whose sum is greater than the given value

Given two Binary Search Tree (BSTs) and a value X, the problem is to print all pairs from both the BSTs whose sum is greater than the given value X.

Examples:

Input: 
BST 1:
                  5        
                /   \      
               3     7      
              / \   / \    
             2  4  6   8   
BST 2:
                 10        
                /   \      
               6     15      
              / \   /  \    
             3  8  11  18
X = 20
Output: The pairs are:
        (3, 18)
        (4, 18)
        (5, 18)
        (6, 18)
        (7, 18)
        (8, 18)
        (6, 15)
        (7, 15)
        (8, 15)

Naive Approach: For each node value A in BST 1, search the value in BST 2 which is greater than the (X – A). If the value is found then print the pair.

Time complexity: O(n1 * h2), where n1 is the number of nodes in first BST and h2 is the height of the second BST.

Efficient Approach:



  1. Traverse BST 1 from smallest value to node to largest by taking index i. This can be achieved with the help of inorder traversal.
  2. Traverse BST 2 from largest value node to smallest by taking index j. This can be achieved with the help of inorder traversal.
  3. Perform these two traversals one by one and store into two array.
  4. Sum up the corresponding node’s value from both the BSTs at a particular instance of traversals.

    • If sum > x, then print pair and decrement j by 1.
    • If x > sum, then increment i by 1.

    Perform these operations until either of the two traversals gets completed.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to print pairs
// from two BSTs whose sum is greater
// the given value x
  
#include <bits/stdc++.h>
using namespace std;
  
// Structure of each node of BST
struct node {
    int key;
    struct node *left, *right;
};
  
// Function to create a new BST node
node* newNode(int item)
{
    node* temp = new node();
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}
  
// A utility function to insert a
// new node with given key in BST
struct node* insert(struct node* node,
                    int key)
{
    // If the tree is empty, return a new node
    if (node == NULL)
        return newNode(key);
  
    // Otherwise, recur down the tree
    if (key < node->key)
        node->left = insert(node->left,
                            key);
    else if (key > node->key)
        node->right = insert(node->right,
                             key);
  
    // Return the (unchanged) node pointer
    return node;
}
  
// Function to return the size of
// the tree
int sizeOfTree(node* root)
{
    if (root == NULL) {
        return 0;
    }
  
    // Calculate left size recursively
    int left = sizeOfTree(root->left);
  
    // Calculate right size recursively
    int right = sizeOfTree(root->right);
  
    // Return total size recursively
    return (left + right + 1);
}
  
// Function to store inorder
// traversal of BST
void storeInorder(node* root,
                  int inOrder[],
                  int& index)
{
    // Base condition
    if (root == NULL) {
        return;
    }
  
    // Left recursive call
    storeInorder(root->left,
                 inOrder,
                 index);
  
    // Store elements in inorder array
    inOrder[index++] = root->key;
  
    // Right recursive call
    storeInorder(root->right,
                 inOrder,
                 index);
}
  
// Function to print the pairs
void print(int inOrder1[], int i,
           int index1, int value)
{
    while (i < index1) {
        cout << "(" << inOrder1[i]
             << ", " << value
             << ")" << endl;
        i++;
    }
}
  
// Utility function to check the
// pair of BSTs whose sum is
// greater than given value x
void printPairUtil(int inOrder1[],
                   int inOrder2[],
                   int index1,
                   int j, int k)
{
    int i = 0;
  
    while (i < index1 && j >= 0) {
  
        if (inOrder1[i] + inOrder2[j] > k) {
            print(inOrder1, i,
                  index1, inOrder2[j]);
            j--;
        }
        else {
            i++;
        }
    }
}
  
// Function to check the
// pair of BSTs whose sum is
// greater than given value x
void printPairs(node* root1,
                node* root2, int k)
{
    // Store the size of BST1
    int numNode = sizeOfTree(root1);
  
    // Take auxiliary array for storing
    // The inorder traversal of BST1
    int inOrder1[numNode + 1];
    int index1 = 0;
  
    // Store the size of BST2
    numNode = sizeOfTree(root2);
  
    // Take auxiliary array for storing
    // The inorder traversal of BST2
    int inOrder2[numNode + 1];
    int index2 = 0;
  
    // Function call for storing
    // inorder traversal of BST1
    storeInorder(root1, inOrder1,
                 index1);
  
    // Function call for storing
    // inorder traversal of BST1
    storeInorder(root2, inOrder2,
                 index2);
  
    // Utility function call to count
    // the pair
    printPairUtil(inOrder1, inOrder2,
                  index1, index2 - 1, k);
}
  
// Driver code
int main()
{
  
    /* Formation of BST 1 
             5
           /   \      
          3     7     
         / \   / \    
         2  4  6  8  
    */
  
    struct node* root1 = NULL;
    root1 = insert(root1, 5);
    insert(root1, 3);
    insert(root1, 2);
    insert(root1, 4);
    insert(root1, 7);
    insert(root1, 6);
    insert(root1, 8);
  
    /* Formation of BST 2 
            10
           /   \      
          6     15     
         / \   / \    
        3   8 11  18  
    */
  
    struct node* root2 = NULL;
    root2 = insert(root2, 10);
    insert(root2, 6);
    insert(root2, 15);
    insert(root2, 3);
    insert(root2, 8);
    insert(root2, 11);
    insert(root2, 18);
  
    int x = 20;
  
    // Print pairs
    printPairs(root1, root2, x);
  
    return 0;
}

chevron_right


Output:

(3, 18)
(4, 18)
(5, 18)
(6, 18)
(7, 18)
(8, 18)
(6, 15)
(7, 15)
(8, 15)

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.