Open In App

Nodes from given two BSTs with sum equal to X

Last Updated : 18 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given two Binary search trees and an integer X, the task is to find a pair of nodes, one belonging to the first BST and the second belonging to other such that their sum is equal to X. If there exists such a pair, print Yes else print No.

Examples: 

Input: X = 100
BST 1:
          5 
        /   \ 
       3     7 
      / \   / \ 
     2   4 6   8
BST 2:
     11
      \
       13
Output: No
There is no such pair with given value.

Input: X = 16
BST 1:
          5 
        /   \ 
       3     7 
      / \   / \ 
     2   4 6   8
BST 2:
     11
      \
       13
Output: Yes
5 + 11 = 16

Approach: We will solve this problem using two pointer approach. 
We will create a forward iterator on the first BST and backward on the second. Thus, we will maintain forward and a backward iterator that will iterate the BSTs in the order of in-order and reverse in-order traversal respectively. 

  1. Create a forward and backward iterator for first and second BST respectively. Let’s say the value of nodes they are pointing at are v1 and v2.
  2. Now at each step, 
    • If v1 + v2 = X, we found a pair.
    • If v1 + v2 less than or equal to x, we will make forward iterator point to the next element.
    • If v1 + v2 greater than x, we will make backward iterator point to the previous element.
  3. We will continue the above while both iterators are pointing to a valid node.

Below is the implementation of the above approach:  

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Node of the binary tree
struct node {
    int data;
    node* left;
    node* right;
    node(int data)
    {
        this->data = data;
        left = NULL;
        right = NULL;
    }
};
 
// Function that returns true if a pair
// with given sum exists in the given BSTs
bool existsPair(node* root1, node* root2, int x)
{
    // Stack to store nodes for forward and backward
    // iterator
    stack<node *> it1, it2;
 
    // Initializing forward iterator
    node* c = root1;
    while (c != NULL)
        it1.push(c), c = c->left;
 
    // Initializing backward iterator
    c = root2;
    while (c != NULL)
        it2.push(c), c = c->right;
 
    // Two pointer technique
    while (it1.size() and it2.size()) {
 
        // To store the value of the nodes
        // current iterators are pointing to
        int v1 = it1.top()->data, v2 = it2.top()->data;
 
        // If found a valid pair
        if (v1 + v2 == x)
            return true;
 
        // Moving forward iterator
        if (v1 + v2 < x) {
            c = it1.top()->right;
            it1.pop();
            while (c != NULL)
                it1.push(c), c = c->left;
        }
 
        // Moving backward iterator
        else {
            c = it2.top()->left;
            it2.pop();
            while (c != NULL)
                it2.push(c), c = c->right;
        }
    }
 
    // If no such pair found
    return false;
}
 
// Driver code
int main()
{
 
    // First BST
    node* root1 = new node(11);
    root1->right = new node(15);
 
    // Second BST
    node* root2 = new node(5);
    root2->left = new node(3);
    root2->right = new node(7);
    root2->left->left = new node(2);
    root2->left->right = new node(4);
    root2->right->left = new node(6);
    root2->right->right = new node(8);
 
    int x = 23;
 
    if (existsPair(root1, root2, x))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Node of the binary tree
static class node
{
    int data;
    node left;
    node right;
    node(int data)
    {
        this.data = data;
        left = null;
        right = null;
    }
};
 
// Function that returns true if a pair
// with given sum exists in the given BSTs
static boolean existsPair(node root1, node root2, int x)
{
    // Stack to store nodes for forward and backward
    // iterator
    Stack<node> it1 = new Stack(), it2 = new Stack();
 
    // Initializing forward iterator
    node c = root1;
    while (c != null)
    {
        it1.push(c);
        c = c.left;
    }
    // Initializing backward iterator
    c = root2;
    while (c != null)
    {
        it2.push(c);
        c = c.right;
    }
 
    // Two pointer technique
    while (it1.size() > 0 && it2.size() > 0)
    {
 
        // To store the value of the nodes
        // current iterators are pointing to
        int v1 = it1.peek().data, v2 = it2.peek().data;
 
        // If found a valid pair
        if (v1 + v2 == x)
            return true;
 
        // Moving forward iterator
        if (v1 + v2 < x)
        {
            c = it1.peek().right;
            it1.pop();
            while (c != null)
            {
                it1.push(c); c = c.left;
            }
        }
 
        // Moving backward iterator
        else
        {
            c = it2.peek().left;
            it2.pop();
            while (c != null)
            {
                it2.push(c); c = c.right;
            }
        }
    }
 
    // If no such pair found
    return false;
}
 
// Driver code
public static void main(String[] args)
{
    // First BST
    node root1 = new node(11);
    root1.right = new node(15);
 
    // Second BST
    node root2 = new node(5);
    root2.left = new node(3);
    root2.right = new node(7);
    root2.left.left = new node(2);
    root2.left.right = new node(4);
    root2.right.left = new node(6);
    root2.right.right = new node(8);
 
    int x = 23;
 
    if (existsPair(root1, root2, x))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by Princi Singh


Python3




# Python3 implementation of the approach
 
# Node of the binary tree
class node:
     
    def __init__ (self, key):
         
        self.data = key
        self.left = None
        self.right = None
 
# Function that returns true if a pair
# with given sum exists in the given BSTs
def existsPair(root1, root2, x):
     
    # Stack to store nodes for forward
    # and backward iterator
    it1, it2 = [], []
 
    # Initializing forward iterator
    c = root1
    while (c != None):
        it1.append(c)
        c = c.left
 
    # Initializing backward iterator
    c = root2
    while (c != None):
        it2.append(c)
        c = c.right
 
    # Two pointer technique
    while (len(it1) > 0 and len(it2) > 0):
 
        # To store the value of the nodes
        # current iterators are pointing to
        v1 = it1[-1].data
        v2 = it2[-1].data
 
        # If found a valid pair
        if (v1 + v2 == x):
            return True
 
        # Moving forward iterator
        if (v1 + v2 < x):
            c = it1[-1].right
            del it1[-1]
             
            while (c != None):
                it1.append(c)
                c = c.left
 
        # Moving backward iterator
        else:
            c = it2[-1].left
            del it2[-1]
             
            while (c != None):
                it2.append(c)
                c = c.right
 
    # If no such pair found
    return False
 
# Driver code
if __name__ == '__main__':
 
    # First BST
    root1 = node(11)
    root1.right = node(15)
 
    # Second BST
    root2 = node(5)
    root2.left = node(3)
    root2.right = node(7)
    root2.left.left = node(2)
    root2.left.right = node(4)
    root2.right.left = node(6)
    root2.right.right = node(8)
 
    x = 23
 
    if (existsPair(root1, root2, x)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by mohit kumar 29


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
     
class GFG
{
 
// Node of the binary tree
public class node
{
    public int data;
    public node left;
    public node right;
    public node(int data)
    {
        this.data = data;
        left = null;
        right = null;
    }
};
 
// Function that returns true if a pair
// with given sum exists in the given BSTs
static bool existsPair(node root1, node root2, int x)
{
    // Stack to store nodes for forward and backward
    // iterator
    Stack<node> it1 = new Stack<node>(), it2 = new Stack<node>();
 
    // Initializing forward iterator
    node c = root1;
    while (c != null)
    {
        it1.Push(c);
        c = c.left;
    }
     
    // Initializing backward iterator
    c = root2;
    while (c != null)
    {
        it2.Push(c);
        c = c.right;
    }
 
    // Two pointer technique
    while (it1.Count > 0 && it2.Count > 0)
    {
 
        // To store the value of the nodes
        // current iterators are pointing to
        int v1 = it1.Peek().data, v2 = it2.Peek().data;
 
        // If found a valid pair
        if (v1 + v2 == x)
            return true;
 
        // Moving forward iterator
        if (v1 + v2 < x)
        {
            c = it1.Peek().right;
            it1.Pop();
            while (c != null)
            {
                it1.Push(c); c = c.left;
            }
        }
 
        // Moving backward iterator
        else
        {
            c = it2.Peek().left;
            it2.Pop();
            while (c != null)
            {
                it2.Push(c); c = c.right;
            }
        }
    }
 
    // If no such pair found
    return false;
}
 
// Driver code
public static void Main(String[] args)
{
    // First BST
    node root1 = new node(11);
    root1.right = new node(15);
 
    // Second BST
    node root2 = new node(5);
    root2.left = new node(3);
    root2.right = new node(7);
    root2.left.left = new node(2);
    root2.left.right = new node(4);
    root2.right.left = new node(6);
    root2.right.right = new node(8);
 
    int x = 23;
 
    if (existsPair(root1, root2, x))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
// Javascript implementation of the approach
 
// Node of the binary tree
class node
{
    constructor(data)
    {
        this.data = data;
        this.left = null;
        this.right = null;
    }
}
 
// Function that returns true if a pair
// with given sum exists in the given BSTs
function existsPair(root1,root2,x)
{
    // Stack to store nodes for forward and backward
    // iterator
    let it1 =[], it2 = [];
  
    // Initializing forward iterator
    let c = root1;
    while (c != null)
    {
        it1.push(c);
        c = c.left;
    }
    // Initializing backward iterator
    c = root2;
    while (c != null)
    {
        it2.push(c);
        c = c.right;
    }
  
    // Two pointer technique
    while (it1.length > 0 && it2.length > 0)
    {
  
        // To store the value of the nodes
        // current iterators are pointing to
        let v1 = it1[it1.length-1].data, v2 = it2[it2.length-1].data;
  
        // If found a valid pair
        if (v1 + v2 == x)
            return true;
  
        // Moving forward iterator
        if (v1 + v2 < x)
        {
            c = it1[it1.length-1].right;
            it1.pop();
            while (c != null)
            {
                it1.push(c); c = c.left;
            }
        }
  
        // Moving backward iterator
        else
        {
            c = it2[it2.length-1].left;
            it2.pop();
            while (c != null)
            {
                it2.push(c); c = c.right;
            }
        }
    }
  
    // If no such pair found
    return false;
}
// Driver code
 
// First BST
    let root1 = new node(11);
    root1.right = new node(15);
  
    // Second BST
    let root2 = new node(5);
    root2.left = new node(3);
    root2.right = new node(7);
    root2.left.left = new node(2);
    root2.left.right = new node(4);
    root2.right.left = new node(6);
    root2.right.right = new node(8);
  
    let x = 23;
  
    if (existsPair(root1, root2, x))
        document.write("Yes");
    else
        document.write("No");
                                 
// This code is contributed by patel2127
</script>


Output: 

Yes

 

Time complexity: O(N)
Auxiliary Space: O(N)  



Similar Reads

Count pairs from two BSTs whose sum is equal to a given value x
Given two BSTs containing n1 and n2 distinct nodes respectively. Given a value x. The problem is to count all pairs from both the BSTs whose sum is equal to x. Examples: Input : BST 1: 5 / \ 3 7 / \ / \ 2 4 6 8 BST 2: 10 / \ 6 15 / \ / \ 3 8 11 18 x = 16 Output : 3 The pairs are: (5, 11), (6, 10) and (8, 8)Recommended PracticeBrothers From Differen
39 min read
Count of BSTs having N nodes and maximum depth equal to H
Given two integers N and H, the task is to find the count of distinct Binary Search Trees consisting of N nodes where the maximum depth or height of the tree is equal to H. Note: The height of BST with only the root node is 0. Examples: Input: N = 2, H = 1Output: 2Explanation: The two BST's are : [caption width="800"]BST's of height H = 1 and nodes
19 min read
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 18X = 20Output: The pairs are: (3, 18) (4, 18) (5, 18) (6, 18) (7, 18) (8, 18) (6, 15) (7, 15) (8, 15)Naive Approach
30 min read
Count of BSTs with N nodes having height at least K
Given two positive integers N and K, the task is to find the number of binary search trees (BST) with N nodes of height greater than or equal to K. Note: Here height refers to the maximum depth of the BST. Examples: Input: N = 3, K = 3Output: 4Explanation:There are 4 possible binary search trees with height greater than or equal to K. 1 1 3 3 \ \ /
6 min read
Check if two given key sequences construct same BSTs
Given two arrays which represent two sequences of keys that are used to create BSTs. Imagine we make a Binary Search Tree (BST) from each array. We need to tell whether two BSTs will be identical or not without actually constructing the tree. Examples: Let the input arrays be a[] and b[] Example 1: a[] = {2, 4, 1, 3} will construct following tree.
6 min read
Generate two BSTs from the given array such that maximum height among them is minimum
Given an array of n integers where n is greater than 1, the task is to make two Binary Search Tree from the given array (in any order) such that the maximum height among the two trees is minimum possible and print the maximum height.Examples: Input: arr[] = {1, 2, 3, 4, 6} Output: 1 Input: arr[] = { 74, 25, 23, 1, 65, 2, 8, 99 } Output: 2 Approach:
4 min read
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 sec
14 min read
Split a BST into two balanced BSTs based on a value K
Given a Binary Search tree and an integer K, we have to split the tree into two Balanced Binary Search Tree, where BST-1 consists of all the nodes which are less than K and BST-2 consists of all the nodes which are greater than or equal to K.Note: The arrangement of the nodes may be anything but both BST should be Balanced. Examples: Input: 40 / \
18 min read
Merge two BSTs with limited extra space
Given two Binary Search Trees(BST), print the inorder traversal of merged BSTs. Examples: Input: First BST 3 / \ 1 5Second BST 4 / \2 6Output: 1 2 3 4 5 6 Input:First BST 8 / \ 2 10 / 1Second BST 5 / 3 /0Output: 0 1 2 3 5 8 10 Recommended PracticeMerge two BST 'sTry It!Merge two BSTs using Iterative Inorder Traversal: The idea is to use iterative i
36 min read
Check if two BSTs contain same set of elements
Given two Binary Search Trees consisting of unique positive elements, we have to check whether the two BSTs contain the same set of elements or not. Note: The structure of the two given BSTs can be different. For example, The above two BSTs contains same set of elements {5, 10, 12, 15, 20, 25} Method 1: The most simple method will be to traverse fi
15 min read