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.
Below is the implementation of the approach:
C++
// 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 BSTstruct node {Â Â Â Â int key;Â Â Â Â struct node *left, *right;};Â
// Function to create a new BST nodenode* 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 BSTstruct 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 treeint 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 BSTvoid 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);}Â
// Utility function to check the// pair of BSTs whose sum is// greater than given value xvoid printPairUtil(int inOrder1[], int inOrder2[],                   int index1, int index2, int k){    // loop through every pairs formed from    // inOrder1 and inOrder2 elements    for (int i = 0; i < index1; i++) {        for (int j = 0; j < index2; j++) {            // store sum of the pairs            int sum = inOrder1[i] + inOrder2[j];Â
            // if sum comes out to be greater than X            // print the pair            if (sum > k)                cout << "(" << inOrder1[i] << ", "                     << inOrder2[j] << ")" << endl;        }    }}Â
// Function to check the// pair of BSTs whose sum is// greater than given value xvoid 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, k);}Â
// Driver codeint 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;} |
Java
// Java implementation to print pairs// from two BSTs whose sum is greater// the given value xÂ
// Structure of each Node of BSTclass Node {Â Â Â Â int key;Â Â Â Â Node left, right;}Â
class RefInteger {Â Â Â Â Integer value;Â
    public RefInteger(Integer value) { this.value = value; }}Â
class GFG {    // Function to create a new BST Node    static 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    static Node insert(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    static 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    static void storeInorder(Node root, int inOrder[],                             RefInteger index)    {        // Base condition        if (root == null) {            return;        }Â
        // Left recursive call        storeInorder(root.left, inOrder, index);Â
        // Store elements in inorder array        inOrder[index.value++] = root.key;Â
        // Right recursive call        storeInorder(root.right, inOrder, index);    }Â
    // Utility function to check the    // pair of BSTs whose sum is    // greater than given value x    static void printPairUtil(int inOrder1[],                              int inOrder2[], int index1,                              int index2, int k)    {        // loop through every pairs formed from inOrder1 and        // inOrder2 elements        for (int i = 0; i < index1; i++) {            for (int j = 0; j < index2; j++) {                // store sum of the pairs                int sum = inOrder1[i] + inOrder2[j];Â
                // if sum comes out to be greater than k,                // print the pair                if (sum > k)                    System.out.println("(" + inOrder1[i]                                       + ", " + inOrder2[j]                                       + ")");            }        }    }Â
    // Function to check the pair of    // BSTs whose sum is greater than    // given value x    static 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 = new int[numNode + 1];        RefInteger index1 = new RefInteger(0);Â
        // Store the size of BST2        numNode = sizeOfTree(root2);Â
        // Take auxiliary array for storing        // The inorder traversal of BST2        int[] inOrder2 = new int[numNode + 1];        RefInteger index2 = new RefInteger(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.value,                      index2.value, k);    }Â
    // Driver code    public static void main(String[] args)    {Â
        /* Formation of BST 1                5        / \        3    7        / \ / \        2 4 6 8        */Â
        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        */Â
        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);    }} |
Python3
# Python3 implementation to print pairs# from two BSTs whose sum is greater# the given value xÂ
index = 0Â
# Structure of each node of BSTclass newNode:Â
    def __init__(self, item):Â
        self.key = item        self.left = None        self.right = NoneÂ
# A utility function to insert a# new node with given key in BSTdef insert(node, key):Â
    # If the tree is empty,    # return a new node    if (node == None):        return newNode(key)Â
    # Otherwise, recur down the tree    if (key < node.key):        node.left = insert(node.left, key)    elif (key > node.key):        node.right = insert(node.right, key)Â
    # Return the (unchanged) node pointer    return nodeÂ
# Function to return the size of# the treedef sizeOfTree(root):Â
    if (root == None):        return 0Â
    # Calculate left size recursively    left = sizeOfTree(root.left)Â
    # Calculate right size recursively    right = sizeOfTree(root.right)Â
    # Return total size recursively    return (left + right + 1)Â
# Function to store inorder# traversal of BSTdef storeInorder(root, inOrder):Â
    global indexÂ
    # Base condition    if (root == None):        returnÂ
    # Left recursive call    storeInorder(root.left, inOrder)Â
    # Store elements in inorder array    inOrder[index] = root.key    index += 1Â
    # Right recursive call    storeInorder(root.right, inOrder)Â
# Utility function to check the# pair of BSTs whose sum is# greater than given value xdef printPairUtil(inOrder1, inOrder2, index1, index2, k):         # loop through every pairs formed from    # inOrder1 and inOrder2 elementsÂ
    for i in range(index1):        for j in range(index2):            # store sum of the pairs            _sum = inOrder1[i] + inOrder2[j]                         # if sum comes out to be greater than X            # print the pair            if _sum > k:                print("(", inOrder1[i], ",", inOrder2[j], ")")           Â
# Function to check the# pair of BSTs whose sum is# greater than given value xdef printPairs(root1, root2, k):         global index         # Store the size of BST1    numNode = sizeOfTree(root1)Â
    # Take auxiliary array for storing    # The inorder traversal of BST1    inOrder1 = [0 for i in range(numNode + 1)]    index1 = 0Â
    # Store the size of BST2    numNode = sizeOfTree(root2)Â
    # Take auxiliary array for storing    # The inorder traversal of BST2    inOrder2 = [0 for i in range(numNode + 1)]    index2 = 0Â
    # Function call for storing    # inorder traversal of BST1    index = 0    storeInorder(root1, inOrder1)    temp1 = indexÂ
    # Function call for storing    # inorder traversal of BST1    index = 0    storeInorder(root2, inOrder2)    temp2 = indexÂ
    # Utility function call to count    # the pair    printPairUtil(inOrder1, inOrder2,                temp1, temp2 , k)Â
# Driver codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â ''' Formation of BST 1Â Â Â Â Â Â Â Â Â Â Â Â 5Â Â Â Â Â Â Â Â / \Â Â Â Â Â Â Â Â Â Â Â 3Â Â Â Â 7Â Â Â Â Â Â Â Â Â Â Â / \ / \Â Â Â Â Â Â Â Â Â Â Â 2 4 6 8Â Â Â Â '''Â
    root1 = None    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    '''    root2 = None    root2 = insert(root2, 10)    insert(root2, 6)    insert(root2, 15)    insert(root2, 3)    insert(root2, 8)    insert(root2, 11)    insert(root2, 18)Â
    x = 20Â
    # Print pairs    printPairs(root1, root2, x)     # This code is contributed by Chandramani |
C#
// C# implementation to print pairs// from two BSTs whose sum is greater// the given value xÂ
using System;Â
class GFG{Â
public class Refint{Â Â Â Â public int value;Â
    public Refint(int value)    {        this.value = value;    }}Â
// Structure of each Node of BSTpublic class Node{Â Â Â Â public int key;Â Â Â Â public Node left, right;};Â
// Function to create a new BST Nodestatic 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 BSTstatic Node insert(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 treestatic 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 BSTstatic void storeInorder(Node root, int []inOrder,                        Refint index){         // Base condition    if (root == null)    {        return;    }Â
    // Left recursive call    storeInorder(root.left, inOrder, index);Â
    // Store elements in inorder array    inOrder[index.value++] = root.key;Â
    // Right recursive call    storeInorder(root.right, inOrder, index);}Â
// Function to print the pairsstatic void print(int []inOrder1, int i,                int index1, int value){    while (i < index1)    {Â
        Console.WriteLine("(" + inOrder1[i] +                        ", " + value + ")");        i++;    }}Â
// Utility function to check the// pair of BSTs whose sum is// greater than given value xstatic void printPairUtil(int []inOrder1,                        int []inOrder2,                        int index1, int index2,                        int k){     // loop through every pairs formed from    // inOrder1 and inOrder2 elements    for (int i = 0; i < index1; i++) {        for (int j = 0; j < index2; j++) {            // store sum of the pairs            int sum = inOrder1[i] + inOrder2[j];              // if sum comes out to be greater than X            // print the pair            if (sum > k)                Console.WriteLine("(" + inOrder1[i] +                           ", " + inOrder2[j] + ")" );        }    }}Â
// Function to check the pair of// BSTs whose sum is greater than// given value xstatic 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 = new int[numNode + 1];    Refint index1 = new Refint(0);Â
    // Store the size of BST2    numNode = sizeOfTree(root2);Â
    // Take auxiliary array for storing    // The inorder traversal of BST2    int[] inOrder2 = new int[numNode + 1];    Refint index2 = new Refint(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.value,                index2.value , k);}Â
// Driver codepublic static void Main(string[] args){Â Â Â Â Â Â Â Â Â /* Formation of BST 1Â Â Â Â Â Â Â Â 5Â Â Â Â / \Â Â Â Â Â Â Â 3Â Â Â Â 7Â Â Â Â Â Â Â / \ / \Â Â Â Â 2 4 6 8Â Â Â Â */Â
    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    */Â
    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);}} |
Javascript
class Node {Â Â Â Â constructor(key) {Â Â Â Â Â Â Â Â this.key = key;Â Â Â Â Â Â Â Â this.left = null;Â Â Â Â Â Â Â Â this.right = null;Â Â Â Â }}Â
// Function to insert a new node in BSTfunction insert(root, key) {Â Â Â Â if (root === null) {Â Â Â Â Â Â Â Â return new Node(key);Â Â Â Â }Â
    if (key < root.key) {        root.left = insert(root.left, key);    } else if (key > root.key) {        root.right = insert(root.right, key);    }Â
    return root;}Â
// Function to calculate the size of the treefunction sizeOfTree(root) {Â Â Â Â if (root === null) {Â Â Â Â Â Â Â Â return 0;Â Â Â Â }Â
    let left = sizeOfTree(root.left);    let right = sizeOfTree(root.right);Â
    return left + right + 1;}Â
// Function to store inorder traversal of BSTfunction storeInorder(root, inOrder, index) {Â Â Â Â if (root === null) {Â Â Â Â Â Â Â Â return index;Â Â Â Â }Â
    index = storeInorder(root.left, inOrder, index);    inOrder[index++] = root.key;    index = storeInorder(root.right, inOrder, index);Â
    return index;}Â
// Utility function to check pairs of BSTs whose sum is greater than xfunction printPairUtil(inOrder1, inOrder2, index1, index2, k) {Â Â Â Â let result = [];Â Â Â Â let i = 0;Â Â Â Â let j = index2 - 1;Â
    while (i < index1 && j >= 0) {        let sum = inOrder1[i] + inOrder2[j];Â
        if (sum > k) {            for (let a = i; a < index1; a++) {                for (let b = j; b >= 0; b--) {                    let currSum = inOrder1[a] + inOrder2[b];                    if (currSum > k) {                        result.push(`(${inOrder1[a]}, ${inOrder2[b]})`);                    } else {                        break;                    }                }            }            j--;        } else {            i++;        }    }Â
    return result;}Â
// Function to check pairs of BSTs whose sum is greater than xfunction printPairs(root1, root2, k) {Â Â Â Â let numNode1 = sizeOfTree(root1);Â Â Â Â let inOrder1 = new Array(numNode1);Â Â Â Â let index1 = 0;Â
    let numNode2 = sizeOfTree(root2);    let inOrder2 = new Array(numNode2);    let index2 = 0;Â
    index1 = storeInorder(root1, inOrder1, index1);    index2 = storeInorder(root2, inOrder2, index2);Â
    let pairs = printPairUtil(inOrder1, inOrder2, index1, index2, k);    pairs.forEach(pair => console.log(pair));}Â
Â
let root1 = null;root1 = insert(root1, 5);insert(root1, 3);insert(root1, 2);insert(root1, 4);insert(root1, 7);insert(root1, 6);insert(root1, 8);Â
let root2 = null;root2 = insert(root2, 10);insert(root2, 6);insert(root2, 15);insert(root2, 3);insert(root2, 8);insert(root2, 11);insert(root2, 18);Â
let x = 20;Â
printPairs(root1, root2, x); |
(3, 18) (4, 18) (5, 18) (6, 15) (6, 18) (7, 15) (7, 18) (8, 15) (8, 18)
Time Complexity: O(N1*N2) where N1 and N2 are size of inOrder1 and inOrder2 arrays respectively as two nested loops are executed in printPairUtil function.
Space Complexity: O(N1+N2) as two arrays inOrder1 and inOrder2 are created.
Efficient Approach:Â Â
- Traverse BST 1 from smallest value to node to largest by taking index i. This can be achieved with the help of inorder traversal.
- Traverse BST 2 from largest value node to smallest by taking index j. This can be achieved with the help of inorder traversal.
- Perform these two traversals one by one and store into two array.
- 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.
Below is the implementation of the above approach:Â Â
C++
// 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 BSTstruct node {Â Â Â Â int key;Â Â Â Â struct node *left, *right;};Â
// Function to create a new BST nodenode* 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 BSTstruct 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 treeint 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 BSTvoid 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 pairsvoid 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 xvoid 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 xvoid 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 codeint 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;} |
Java
// Java implementation to print pairs// from two BSTs whose sum is greater// the given value xclass GFG{Â
static class RefInteger{Â Â Â Â Integer value;Â
    public RefInteger(Integer value)     {        this.value = value;    }}Â
// Structure of each Node of BSTstatic class Node {Â Â Â Â int key;Â Â Â Â Node left, right;};Â
// Function to create a new BST Nodestatic 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 BSTstatic Node insert(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 treestatic 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 BSTstatic void storeInorder(Node root, int inOrder[],                         RefInteger index) {         // Base condition    if (root == null)     {        return;    }Â
    // Left recursive call    storeInorder(root.left, inOrder, index);Â
    // Store elements in inorder array    inOrder[index.value++] = root.key;Â
    // Right recursive call    storeInorder(root.right, inOrder, index);}Â
// Function to print the pairsstatic void print(int inOrder1[], int i, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int index1, int value) {Â Â Â Â while (i < index1) Â Â Â Â {Â Â Â Â Â Â Â Â System.out.println("(" + inOrder1[i] + Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ", " + value + ")");Â Â Â Â Â Â Â Â i++;Â Â Â Â }}Â
// Utility function to check the// pair of BSTs whose sum is// greater than given value xstatic 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 xstatic 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 = new int[numNode + 1];    RefInteger index1 = new RefInteger(0);Â
    // Store the size of BST2    numNode = sizeOfTree(root2);Â
    // Take auxiliary array for storing    // The inorder traversal of BST2    int[] inOrder2 = new int[numNode + 1];    RefInteger index2 = new RefInteger(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.value,                   index2.value - 1, k);}Â
// Driver codepublic static void main(String[] args) {Â Â Â Â Â Â Â Â Â /* Formation of BST 1 Â Â Â Â Â Â Â Â Â 5Â Â Â Â Â Â Â /Â Â \Â Â Â Â Â Â Â Â Â Â Â 3Â Â Â Â 7Â Â Â Â Â Â Â Â Â / \Â Â / \Â Â Â Â Â Â Â 2Â 4Â 6Â Â 8Â Â Â Â Â */Â
    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     */Â
    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);}}Â
// This code is contributed by sanjeev2552 |
Python3
# Python3 implementation to print pairs# from two BSTs whose sum is greater# the given value xindex = 0Â
# Structure of each node of BSTclass newNode:         def __init__(self, item):                 self.key = item        self.left = None        self.right = NoneÂ
# A utility function to insert a# new node with given key in BSTdef insert(node, key):         # If the tree is empty,     # return a new node    if (node == None):        return newNode(key)Â
    # Otherwise, recur down the tree    if (key < node.key):        node.left = insert(node.left, key)    elif (key > node.key):        node.right = insert(node.right, key)Â
    # Return the (unchanged) node pointer    return nodeÂ
# Function to return the size of# the treedef sizeOfTree(root):         if (root == None):        return 0             # Calculate left size recursively    left = sizeOfTree(root.left)Â
    # Calculate right size recursively    right = sizeOfTree(root.right)Â
    # Return total size recursively    return (left + right + 1)Â
# Function to store inorder# traversal of BSTdef storeInorder(root, inOrder):         global index         # Base condition    if (root == None):        returnÂ
    # Left recursive call    storeInorder(root.left, inOrder)Â
    # Store elements in inorder array    inOrder[index] = root.key    index += 1Â
    # Right recursive call    storeInorder(root.right, inOrder)Â
# Function to print the pairsdef print1(inOrder1, i, index1, value):Â Â Â Â Â Â Â Â Â while (i < index1):Â Â Â Â Â Â Â Â print("(", inOrder1[i], ",", value, ")")Â Â Â Â Â Â Â Â i += 1Â
# Utility function to check the# pair of BSTs whose sum is# greater than given value xdef printPairUtil(inOrder1, inOrder2,                  index1, j, k):                           i = 0Â
    while (i < index1 and j >= 0):        if (inOrder1[i] + inOrder2[j] > k):            print1(inOrder1, i, index1, inOrder2[j])            j -= 1        else:            i += 1Â
# Function to check the# pair of BSTs whose sum is# greater than given value xdef printPairs(root1, root2, k):         global index         # Store the size of BST1    numNode = sizeOfTree(root1)Â
    # Take auxiliary array for storing    # The inorder traversal of BST1    inOrder1 = [0 for i in range(numNode + 1)]    index1 = 0Â
    # Store the size of BST2    numNode = sizeOfTree(root2)Â
    # Take auxiliary array for storing    # The inorder traversal of BST2    inOrder2 = [0 for i in range(numNode + 1)]    index2 = 0Â
    # Function call for storing    # inorder traversal of BST1    index = 0    storeInorder(root1, inOrder1)    temp1 = indexÂ
    # Function call for storing    # inorder traversal of BST1    index = 0    storeInorder(root2, inOrder2)    temp2 = indexÂ
    # Utility function call to count    # the pair    printPairUtil(inOrder1, inOrder2,                   temp1, temp2 - 1, k)Â
# Driver codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â ''' Formation of BST 1 Â Â Â Â Â Â Â Â Â Â Â Â Â 5 Â Â Â Â Â Â Â Â Â Â Â /Â Â \Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 3Â Â Â Â 7Â Â Â Â Â Â Â Â Â Â Â Â Â Â / \Â Â / \Â Â Â Â Â Â Â Â Â Â Â Â Â 2Â 4Â 6Â 8Â Â Â Â Â Â '''Â
    root1 = None    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      '''    root2 = None    root2 = insert(root2, 10)    insert(root2, 6)    insert(root2, 15)    insert(root2, 3)    insert(root2, 8)    insert(root2, 11)    insert(root2, 18)Â
    x = 20Â
    # Print pairs    printPairs(root1, root2, x)     # This code is contributed by ipg2016107 |
C#
// C# implementation to print pairs// from two BSTs whose sum is greater// the given value xÂ
using System;Â
class GFG{  public class Refint{    public int value;      public Refint(int value)     {        this.value = value;    }}  // Structure of each Node of BSTpublic class Node {    public int key;    public Node left, right;};  // Function to create a new BST Nodestatic 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 BSTstatic Node insert(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 treestatic 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 BSTstatic void storeInorder(Node root, int []inOrder,                         Refint index) {          // Base condition    if (root == null)     {        return;    }      // Left recursive call    storeInorder(root.left, inOrder, index);      // Store elements in inorder array    inOrder[index.value++] = root.key;      // Right recursive call    storeInorder(root.right, inOrder, index);}  // Function to print the pairsstatic void print(int []inOrder1, int i,                   int index1, int value) {    while (i < index1)     {Â
        Console.WriteLine("(" + inOrder1[i] +                            ", " + value + ")");        i++;    }}  // Utility function to check the// pair of BSTs whose sum is// greater than given value xstatic 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 xstatic 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 = new int[numNode + 1];    Refint index1 = new Refint(0);      // Store the size of BST2    numNode = sizeOfTree(root2);      // Take auxiliary array for storing    // The inorder traversal of BST2    int[] inOrder2 = new int[numNode + 1];    Refint index2 = new Refint(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.value,                   index2.value - 1, k);}  // Driver codepublic static void Main(string[] args) {          /* Formation of BST 1          5       /  \           3    7         / \  / \       2 4 6  8     */      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     */      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);}}Â
// This code is contributed by rutvik_56 |
Javascript
<script>Â
    // JavaScript implementation to print pairs    // from two BSTs whose sum is greater    // the given value x         class Refint    {        constructor(value)        {            this.value = value;        }    }Â
    // Structure of each Node of BST    class Node    {        constructor(item) {           this.left = null;           this.right = null;           this.key = item;        }    }Â
    // Function to create a new BST Node    function newNode(item)    {        let temp = new Node(item);        return temp;    }Â
    // A utility function to insert a    // new Node with given key in BST    function insert(Node, 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    function sizeOfTree(root)    {        if (root == null)        {            return 0;        }Â
        // Calculate left size recursively        let left = sizeOfTree(root.left);Â
        // Calculate right size recursively        let right = sizeOfTree(root.right);Â
        // Return total size recursively        return (left + right + 1);    }Â
    // Function to store inorder    // traversal of BST    function storeInorder(root, inOrder, index)    {Â
        // Base condition        if (root == null)        {            return;        }Â
        // Left recursive call        storeInorder(root.left, inOrder, index);Â
        // Store elements in inorder array        inOrder[index.value++] = root.key;Â
        // Right recursive call        storeInorder(root.right, inOrder, index);    }Â
    // Function to print the pairs    function print(inOrder1, i, index1, value)    {        while (i < index1)        {Â
            document.write("(" + inOrder1[i] +                               ", " + value + ")" + "</br>");            i++;        }    }Â
    // Utility function to check the    // pair of BSTs whose sum is    // greater than given value x    function printPairUtil(inOrder1, inOrder2, index1, j, k)    {        let 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    function printPairs(root1, root2, k)    {Â
        // Store the size of BST1        let numNode = sizeOfTree(root1);Â
        // Take auxiliary array for storing        // The inorder traversal of BST1        let inOrder1 = new Array(numNode + 1);        let index1 = new Refint(0);Â
        // Store the size of BST2        numNode = sizeOfTree(root2);Â
        // Take auxiliary array for storing        // The inorder traversal of BST2        let inOrder2 = new Array(numNode + 1);        let index2 = new Refint(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.value,                      index2.value - 1, k);    }         /* Formation of BST 1         5       /  \          3    7        / \  / \      2 4 6  8     */       let 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     */       let root2 = null;    root2 = insert(root2, 10);    insert(root2, 6);    insert(root2, 15);    insert(root2, 3);    insert(root2, 8);    insert(root2, 11);    insert(root2, 18);       let x = 20;       // Print pairs    printPairs(root1, root2, x);Â
</script> |
(3, 18) (4, 18) (5, 18) (6, 18) (7, 18) (8, 18) (6, 15) (7, 15) (8, 15)
Time complexity: O(n1 * h2), where n1 is the number of nodes in the first BST and h2 is the height of the second BST.
Auxiliary Space: O(n), where n is the total number of nodes in the two BSTs
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



