# Count pairs from two BSTs whose sum is equal to a given value x

Last Updated : 19 Apr, 2023

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 Practice

Method 1: For each node value a in BST 1, search the value (x – a) in BST 2. If value found then increment the count. For searching a value in BST.

Implementation

## C++

 `#include ` `#include ` `#include ` `using` `namespace` `std;`   `// Definition of BST node` `struct` `Node {` `    ``int` `data;` `    ``Node *left, *right;` `    ``Node(``int` `x)` `    ``{` `        ``data = x;` `        ``left = right = NULL;` `    ``}` `};`   `// Function to insert a node in BST` `Node* insert(Node* root, ``int` `x)` `{` `    ``if` `(root == NULL)` `        ``return` `new` `Node(x);` `    ``if` `(x < root->data)` `        ``root->left = insert(root->left, x);` `    ``else` `if` `(x > root->data)` `        ``root->right = insert(root->right, x);` `    ``return` `root;` `}`   `// Function to count pairs with sum equal to x` `int` `countPairs(Node* root1, Node* root2, ``int` `x)` `{` `    ``// Set to store values of BST 2` `    ``unordered_set<``int``> s;`   `    ``// Traverse BST 2 and insert values in the set` `    ``stack st;` `    ``Node* curr = root2;` `    ``while` `(curr != NULL || !st.empty()) {` `        ``while` `(curr != NULL) {` `            ``st.push(curr);` `            ``curr = curr->left;` `        ``}` `        ``curr = st.top();` `        ``st.pop();` `        ``s.insert(curr->data);` `        ``curr = curr->right;` `    ``}`   `    ``// Traverse BST 1 and search for (x-a) in the set` `    ``int` `count = 0;` `    ``curr = root1;` `    ``while` `(curr != NULL || !st.empty()) {` `        ``while` `(curr != NULL) {` `            ``st.push(curr);` `            ``curr = curr->left;` `        ``}` `        ``curr = st.top();` `        ``st.pop();` `        ``if` `(s.find(x - curr->data) != s.end())` `            ``count++;` `        ``curr = curr->right;` `    ``}`   `    ``return` `count;` `}`   `// Driver code` `int` `main()` `{` `    ``// Input BSTs` `    ``Node *root1 = NULL, *root2 = NULL;` `    ``root1 = insert(root1, 5);` `    ``root1 = insert(root1, 3);` `    ``root1 = insert(root1, 7);` `    ``root1 = insert(root1, 2);` `    ``root1 = insert(root1, 4);` `    ``root1 = insert(root1, 6);` `    ``root1 = insert(root1, 8);`   `    ``root2 = insert(root2, 10);` `    ``root2 = insert(root2, 6);` `    ``root2 = insert(root2, 15);` `    ``root2 = insert(root2, 3);` `    ``root2 = insert(root2, 8);` `    ``root2 = insert(root2, 11);` `    ``root2 = insert(root2, 18);`   `    ``// Value of x` `    ``int` `x = 16;`   `    ``// Count pairs with sum equal to x` `    ``int` `count = countPairs(root1, root2, x);`   `    ``cout << ``"Count of pairs with sum "` `<< x << ``" is "` `         ``<< count << endl;`   `    ``return` `0;` `}`

## Java

 `import` `java.util.*;`   `// Definition of BST node` `class` `Node {` `    ``int` `data;` `    ``Node left, right;`   `    ``Node(``int` `x)` `    ``{` `        ``data = x;` `        ``left = right = ``null``;` `    ``}` `}`   `class` `Main {`   `    ``// Function to insert a node in BST` `    ``static` `Node insert(Node root, ``int` `x)` `    ``{` `        ``if` `(root == ``null``)` `            ``return` `new` `Node(x);` `        ``if` `(x < root.data)` `            ``root.left = insert(root.left, x);` `        ``else` `if` `(x > root.data)` `            ``root.right = insert(root.right, x);` `        ``return` `root;` `    ``}`   `    ``// Function to count pairs with sum equal to x` `    ``static` `int` `countPairs(Node root1, Node root2, ``int` `x)` `    ``{` `        ``Set set = ``new` `HashSet<>();` `        ``Stack stack = ``new` `Stack<>();` `        ``Node curr = root2;`   `        ``while` `(curr != ``null` `|| !stack.empty()) {` `            ``while` `(curr != ``null``) {` `                ``stack.push(curr);` `                ``curr = curr.left;` `            ``}`   `            ``curr = stack.pop();` `            ``set.add(curr.data);` `            ``curr = curr.right;` `        ``}`   `        ``// Traverse BST 1 and search for (x-a) in the set` `        ``int` `count = ``0``;` `        ``curr = root1;`   `        ``while` `(curr != ``null` `|| !stack.empty()) {` `            ``while` `(curr != ``null``) {` `                ``stack.push(curr);` `                ``curr = curr.left;` `            ``}` `            ``curr = stack.pop();` `            ``if` `(set.contains(x - curr.data))` `                ``count++;` `            ``curr = curr.right;` `        ``}` `        ``return` `count;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{`   `        ``// Input BSTs` `        ``Node root1 = ``null``, root2 = ``null``;` `        ``root1 = insert(root1, ``5``);` `        ``root1 = insert(root1, ``3``);` `        ``root1 = insert(root1, ``7``);` `        ``root1 = insert(root1, ``2``);` `        ``root1 = insert(root1, ``4``);` `        ``root1 = insert(root1, ``6``);` `        ``root1 = insert(root1, ``8``);`   `        ``root2 = insert(root2, ``10``);` `        ``root2 = insert(root2, ``6``);` `        ``root2 = insert(root2, ``15``);` `        ``root2 = insert(root2, ``3``);` `        ``root2 = insert(root2, ``8``);` `        ``root2 = insert(root2, ``11``);` `        ``root2 = insert(root2, ``18``);`   `        ``// Value of x` `        ``int` `x = ``16``;`   `        ``// Count pairs with sum equal to x` `        ``int` `count = countPairs(root1, root2, x);` `        ``System.out.println(``"Count of pairs with sum "` `+ x` `                           ``+ ``" is "` `+ count);` `    ``}` `}`

## Python3

 `# Definition of BST node` `class` `Node:` `    ``def` `__init__(``self``, x):` `        ``self``.data ``=` `x` `        ``self``.left ``=` `None` `        ``self``.right ``=` `None`   `# Function to insert a node in BST`     `def` `insert(root, x):` `    ``if` `root ``is` `None``:` `        ``return` `Node(x)` `    ``if` `x < root.data:` `        ``root.left ``=` `insert(root.left, x)` `    ``elif` `x > root.data:` `        ``root.right ``=` `insert(root.right, x)` `    ``return` `root`   `# Function to count pairs with sum equal to x`     `def` `countPairs(root1, root2, x):` `    ``# Set to store values of BST 2` `    ``s ``=` `set``()`   `    ``# Traverse BST 2 and insert values in the set` `    ``st ``=` `[]` `    ``curr ``=` `root2` `    ``while` `curr ``is` `not` `None` `or` `len``(st) > ``0``:` `        ``while` `curr ``is` `not` `None``:` `            ``st.append(curr)` `            ``curr ``=` `curr.left` `        ``curr ``=` `st.pop()` `        ``s.add(curr.data)` `        ``curr ``=` `curr.right`   `    ``# Traverse BST 1 and search for (x-a) in the set` `    ``count ``=` `0` `    ``curr ``=` `root1` `    ``while` `curr ``is` `not` `None` `or` `len``(st) > ``0``:` `        ``while` `curr ``is` `not` `None``:` `            ``st.append(curr)` `            ``curr ``=` `curr.left` `        ``curr ``=` `st.pop()` `        ``if` `x ``-` `curr.data ``in` `s:` `            ``count ``+``=` `1` `        ``curr ``=` `curr.right`   `    ``return` `count`     `# Driver code` `if` `__name__ ``=``=` `'__main__'``:` `    ``# Input BSTs` `    ``root1, root2 ``=` `None``, ``None` `    ``root1 ``=` `insert(root1, ``5``)` `    ``root1 ``=` `insert(root1, ``3``)` `    ``root1 ``=` `insert(root1, ``7``)` `    ``root1 ``=` `insert(root1, ``2``)` `    ``root1 ``=` `insert(root1, ``4``)` `    ``root1 ``=` `insert(root1, ``6``)` `    ``root1 ``=` `insert(root1, ``8``)`   `    ``root2 ``=` `insert(root2, ``10``)` `    ``root2 ``=` `insert(root2, ``6``)` `    ``root2 ``=` `insert(root2, ``15``)` `    ``root2 ``=` `insert(root2, ``3``)` `    ``root2 ``=` `insert(root2, ``8``)` `    ``root2 ``=` `insert(root2, ``11``)` `    ``root2 ``=` `insert(root2, ``18``)`   `    ``# Value of x` `    ``x ``=` `16` `    ``# Count pairs with sum equal to x` `    ``print``(``"Count of pairs with sum "` `+` `str``(x) ``+` `          ``" is "` `+` `str``(countPairs(root1, root2, x)))`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `// Definition of BST node` `class` `Node {` `    ``public` `int` `data;` `    ``public` `Node left;` `    ``public` `Node right;`   `    ``public` `Node(``int` `x)` `    ``{` `        ``data = x;` `        ``left = ``null``;` `        ``right = ``null``;` `    ``}` `}`   `class` `Program {` `    ``// Function to insert a node in BST` `    ``static` `Node insert(Node root, ``int` `x)` `    ``{` `        ``if` `(root == ``null``) {` `            ``return` `new` `Node(x);` `        ``}` `        ``if` `(x < root.data) {` `            ``root.left = insert(root.left, x);` `        ``}` `        ``else` `if` `(x > root.data) {` `            ``root.right = insert(root.right, x);` `        ``}` `        ``return` `root;` `    ``}`   `    ``// Function to count pairs with sum equal to x` `    ``static` `int` `countPairs(Node root1, Node root2, ``int` `x)` `    ``{` `        ``// Set to store values of BST 2` `        ``HashSet<``int``> s = ``new` `HashSet<``int``>();`   `        ``// Traverse BST 2 and insert values in the set` `        ``Stack st = ``new` `Stack();` `        ``Node curr = root2;` `        ``while` `(curr != ``null` `|| st.Count > 0) {` `            ``while` `(curr != ``null``) {` `                ``st.Push(curr);` `                ``curr = curr.left;` `            ``}` `            ``curr = st.Pop();` `            ``s.Add(curr.data);` `            ``curr = curr.right;` `        ``}`   `        ``// Traverse BST 1 and search for (x-a) in the set` `        ``int` `count = 0;` `        ``curr = root1;` `        ``st.Clear();` `        ``while` `(curr != ``null` `|| st.Count > 0) {` `            ``while` `(curr != ``null``) {` `                ``st.Push(curr);` `                ``curr = curr.left;` `            ``}` `            ``curr = st.Pop();` `            ``if` `(s.Contains(x - curr.data)) {` `                ``count++;` `            ``}` `            ``curr = curr.right;` `        ``}`   `        ``return` `count;` `    ``}`   `    ``// Driver code` `    ``static` `void` `Main(``string``[] args)` `    ``{` `        ``// Input BSTs` `        ``Node root1 = ``null``, root2 = ``null``;` `        ``root1 = insert(root1, 5);` `        ``root1 = insert(root1, 3);` `        ``root1 = insert(root1, 7);` `        ``root1 = insert(root1, 2);` `        ``root1 = insert(root1, 4);` `        ``root1 = insert(root1, 6);` `        ``root1 = insert(root1, 8);`   `        ``root2 = insert(root2, 10);` `        ``root2 = insert(root2, 6);` `        ``root2 = insert(root2, 15);` `        ``root2 = insert(root2, 3);` `        ``root2 = insert(root2, 8);` `        ``root2 = insert(root2, 11);` `        ``root2 = insert(root2, 18);`   `        ``// Value of x` `        ``int` `x = 16;`   `        ``// Count pairs with sum equal to x` `        ``Console.WriteLine(``"Count of pairs with sum "` `+ x` `                          ``+ ``" is "` `                          ``+ countPairs(root1, root2, x));` `    ``}` `}`

## Javascript

 `// Definition of BST node` `class Node {` `    ``constructor(x) {` `        ``this``.data = x;` `        ``this``.left = ``null``;` `        ``this``.right = ``null``;` `    ``}` `}`   `// Function to insert a node in BST` `function` `insert(root, x) {` `    ``if` `(root === ``null``) {` `        ``return` `new` `Node(x);` `    ``}` `    ``if` `(x < root.data) {` `        ``root.left = insert(root.left, x);` `    ``} ``else` `if` `(x > root.data) {` `        ``root.right = insert(root.right, x);` `    ``}` `    ``return` `root;` `}`   `// Function to count pairs with sum equal to x` `function` `countPairs(root1, root2, x) {` `    ``const set = ``new` `Set();` `    ``const stack = [];` `    ``let curr = root2;`   `    ``while` `(curr !== ``null` `|| stack.length !== 0) {` `        ``while` `(curr !== ``null``) {` `            ``stack.push(curr);` `            ``curr = curr.left;` `        ``}`   `        ``curr = stack.pop();` `        ``set.add(curr.data);` `        ``curr = curr.right;` `    ``}`   `    ``// Traverse BST 1 and search for (x-a) in the set` `    ``let count = 0;` `    ``curr = root1;`   `    ``while` `(curr !== ``null` `|| stack.length !== 0) {` `        ``while` `(curr !== ``null``) {` `            ``stack.push(curr);` `            ``curr = curr.left;` `        ``}` `        ``curr = stack.pop();` `        ``if` `(set.has(x - curr.data)) {` `            ``count++;` `        ``}` `        ``curr = curr.right;` `    ``}` `    ``return` `count;` `}`   `// Input BSTs` `let root1 = ``null``,` `    ``root2 = ``null``;` `root1 = insert(root1, 5);` `root1 = insert(root1, 3);` `root1 = insert(root1, 7);` `root1 = insert(root1, 2);` `root1 = insert(root1, 4);` `root1 = insert(root1, 6);` `root1 = insert(root1, 8);`   `root2 = insert(root2, 10);` `root2 = insert(root2, 6);` `root2 = insert(root2, 15);` `root2 = insert(root2, 3);` `root2 = insert(root2, 8);` `root2 = insert(root2, 11);` `root2 = insert(root2, 18);`   `// Value of x` `const x = 16;`   `// Count pairs with sum equal to x` `const count = countPairs(root1, root2, x);` `console.log(``"Count of pairs with sum "` `+ x + ``" is "` `+ count);`

Output

`Count of pairs with sum 16 is 3`

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

Method 2: Traverse BST 1 from smallest value to node to largest. This can be achieved with the help of iterative inorder traversal. Traverse BST 2 from largest value node to smallest. This can be achieved with the help of reverse inorder traversal. Perform these two traversals simultaneously. Sum up the corresponding node’s value from both the BSTs at a particular instance of traversals. If sum == x, then increment count. If x > sum, then move to the inorder successor of the current node of BST 1, else move to the inorder predecessor of the current node of BST 2. Perform these operations until either of the two traversals gets completed.

Implementation:

## C++

 `// C++ implementation to count pairs from two` `// BSTs whose sum is equal to a given  value x` `#include ` `using` `namespace` `std;`   `// structure of a node of BST` `struct` `Node {` `    ``int` `data;` `    ``Node* left, *right;` `};`   `// function to create and return a node of BST` `Node* getNode(``int` `data)` `{` `    ``// allocate space for the node` `    ``Node* new_node = (Node*)``malloc``(``sizeof``(Node));`   `    ``// put in the data` `    ``new_node->data = data;` `    ``new_node->left = new_node->right = NULL;` `}`   `// function to count pairs from two BSTs` `// whose sum is equal to a given value x` `int` `countPairs(Node* root1, Node* root2, ``int` `x)` `{` `    ``// if either of the tree is empty` `    ``if` `(root1 == NULL || root2 == NULL)` `        ``return` `0;`   `    ``// stack 'st1' used for the inorder` `    ``// traversal of BST 1` `    ``// stack 'st2' used for the reverse` `    ``// inorder traversal of BST 2` `    ``stack st1, st2;` `    ``Node* top1, *top2;`   `    ``int` `count = 0;`   `    ``// the loop will break when either of two` `    ``// traversals gets completed` `    ``while` `(1) {`   `        ``// to find next node in inorder` `        ``// traversal of BST 1` `        ``while` `(root1 != NULL) {` `            ``st1.push(root1);` `            ``root1 = root1->left;` `        ``}`   `        ``// to find next node in reverse` `        ``// inorder traversal of BST 2` `        ``while` `(root2 != NULL) {` `            ``st2.push(root2);` `            ``root2 = root2->right;` `        ``}`   `        ``// if either gets empty then corresponding` `        ``// tree traversal is completed` `        ``if` `(st1.empty() || st2.empty())` `            ``break``;`   `        ``top1 = st1.top();` `        ``top2 = st2.top();`   `        ``// if the sum of the node's is equal to 'x'` `        ``if` `((top1->data + top2->data) == x) {` `            ``// increment count` `            ``count++;`   `            ``// pop nodes from the respective stacks` `            ``st1.pop();` `            ``st2.pop();`   `            ``// insert next possible node in the` `            ``// respective stacks` `            ``root1 = top1->right;` `            ``root2 = top2->left;` `        ``}`   `        ``// move to next possible node in the` `        ``// inorder traversal of BST 1` `        ``else` `if` `((top1->data + top2->data) < x) {` `            ``st1.pop();` `            ``root1 = top1->right;` `        ``}`   `        ``// move to next possible node in the` `        ``// reverse inorder traversal of BST 2` `        ``else` `{` `            ``st2.pop();` `            ``root2 = top2->left;` `        ``}` `    ``}`   `    ``// required count of pairs` `    ``return` `count;` `}`   `// Driver program to test above` `int` `main()` `{` `    ``// formation of BST 1` `    ``Node* root1 = getNode(5); ``/*             5        */` `    ``root1->left = getNode(3); ``/*           /   \      */` `    ``root1->right = getNode(7); ``/*         3     7     */` `    ``root1->left->left = getNode(2); ``/*    / \   / \    */` `    ``root1->left->right = getNode(4); ``/*  2  4  6  8    */` `    ``root1->right->left = getNode(6);` `    ``root1->right->right = getNode(8);`   `    ``// formation of BST 2` `    ``Node* root2 = getNode(10); ``/*           10         */` `    ``root2->left = getNode(6); ``/*           /   \        */` `    ``root2->right = getNode(15); ``/*        6     15      */` `    ``root2->left->left = getNode(3); ``/*    / \   /  \     */` `    ``root2->left->right = getNode(8); ``/*  3  8  11  18    */` `    ``root2->right->left = getNode(11);` `    ``root2->right->right = getNode(18);`   `    ``int` `x = 16;` `    ``cout << ``"Pairs = "` `         ``<< countPairs(root1, root2, x);`   `    ``return` `0;` `}`

## Java

 `// Java implementation to count pairs from two` `// BSTs whose sum is equal to a given  value x` `import` `java.util.Stack;` `public` `class` `GFG {`   `    ``// structure of a node of BST` `    ``static` `class` `Node {` `        ``int` `data;` `        ``Node left, right;` `        `  `        ``// constructor` `        ``public` `Node(``int` `data) {` `            ``this``.data = data;` `            ``left = ``null``;` `            ``right = ``null``;` `        ``}` `    ``}` `    `  `    ``static` `Node root1;` `    ``static` `Node root2;` `    ``// function to count pairs from two BSTs` `    ``// whose sum is equal to a given value x` `    ``static` `int` `countPairs(Node root1, Node root2,` `                                           ``int` `x)` `    ``{` `        ``// if either of the tree is empty` `        ``if` `(root1 == ``null` `|| root2 == ``null``)` `            ``return` `0``;` `     `  `        ``// stack 'st1' used for the inorder` `        ``// traversal of BST 1` `        ``// stack 'st2' used for the reverse` `        ``// inorder traversal of BST 2` `        ``//stack st1, st2;` `        ``Stack st1 = ``new` `Stack<>();` `        ``Stack st2 = ``new` `Stack<>();` `        ``Node top1, top2;` `     `  `        ``int` `count = ``0``;` `     `  `        ``// the loop will break when either of two` `        ``// traversals gets completed` `        ``while` `(``true``) {` `     `  `            ``// to find next node in inorder` `            ``// traversal of BST 1` `            ``while` `(root1 != ``null``) {` `                ``st1.push(root1);` `                ``root1 = root1.left;` `            ``}` `     `  `            ``// to find next node in reverse` `            ``// inorder traversal of BST 2` `            ``while` `(root2 != ``null``) {` `                ``st2.push(root2);` `                ``root2 = root2.right;` `            ``}` `     `  `            ``// if either gets empty then corresponding` `            ``// tree traversal is completed` `            ``if` `(st1.empty() || st2.empty())` `                ``break``;` `     `  `            ``top1 = st1.peek();` `            ``top2 = st2.peek();` `     `  `            ``// if the sum of the node's is equal to 'x'` `            ``if` `((top1.data + top2.data) == x) {` `                ``// increment count` `                ``count++;` `     `  `                ``// pop nodes from the respective stacks` `                ``st1.pop();` `                ``st2.pop();` `     `  `                ``// insert next possible node in the` `                ``// respective stacks` `                ``root1 = top1.right;` `                ``root2 = top2.left;` `            ``}` `     `  `            ``// move to next possible node in the` `            ``// inorder traversal of BST 1` `            ``else` `if` `((top1.data + top2.data) < x) {` `                ``st1.pop();` `                ``root1 = top1.right;` `            ``}` `     `  `            ``// move to next possible node in the` `            ``// reverse inorder traversal of BST 2` `            ``else` `{` `                ``st2.pop();` `                ``root2 = top2.left;` `            ``}` `        ``}` `     `  `        ``// required count of pairs` `        ``return` `count;` `    ``}` `     `  `    ``// Driver program to test above` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``// formation of BST 1` `        ``root1 = ``new` `Node(``5``);       ``/*             5        */` `        ``root1.left = ``new` `Node(``3``); ``/*           /   \      */` `        ``root1.right = ``new` `Node(``7``); ``/*         3     7     */` `        ``root1.left.left = ``new` `Node(``2``); ``/*    / \   / \    */` `        ``root1.left.right = ``new` `Node(``4``); ``/*  2   4 6   8    */` `        ``root1.right.left = ``new` `Node(``6``);` `        ``root1.right.right = ``new` `Node(``8``);` `     `  `        ``// formation of BST 2` `        ``root2 = ``new` `Node(``10``);        ``/*           10         */` `        ``root2.left = ``new` `Node(``6``); ``/*           /   \        */` `        ``root2.right = ``new` `Node(``15``); ``/*        6     15      */` `        ``root2.left.left = ``new` `Node(``3``); ``/*    / \   /  \     */` `        ``root2.left.right = ``new` `Node(``8``); ``/*  3  8  11  18    */` `        ``root2.right.left = ``new` `Node(``11``);` `        ``root2.right.right = ``new` `Node(``18``);` `     `  `        ``int` `x = ``16``;` `        ``System.out.println(``"Pairs = "` `             ``+ countPairs(root1, root2, x));` `    ``}` `}` `// This code is contributed by Sumit Ghosh`

## Python3

 `# Python3 implementation to count pairs` `# from two BSTs whose sum is equal to a` `# given  value x`   `# Structure of a node of BST` `class` `getNode:` `    `  `    ``def` `__init__(``self``, data):` `        `  `        ``self``.data ``=` `data` `        ``self``.left ``=` `None` `        ``self``.right ``=` `None`   `# Function to count pairs from two BSTs` `# whose sum is equal to a given value x` `def` `countPairs(root1, root2, x):` `    `  `    ``# If either of the tree is empty` `    ``if` `(root1 ``=``=` `None` `or` `root2 ``=``=` `None``):` `        ``return` `0`   `    ``# Stack 'st1' used for the inorder` `    ``# traversal of BST 1` `    ``# stack 'st2' used for the reverse` `    ``# inorder traversal of BST 2` `    ``st1 ``=` `[]` `    ``st2 ``=` `[]`   `    ``count ``=` `3`   `    ``# The loop will break when either` `    ``# of two traversals gets completed` `    ``while` `(``1``):` `        `  `        ``# To find next node in inorder` `        ``# traversal of BST 1` `        ``while` `(root1 !``=` `None``):` `            ``st1.append(root1)` `            ``root1 ``=` `root1.left`   `        ``# To find next node in reverse` `        ``# inorder traversal of BST 2` `        ``while` `(root2 !``=` `None``):` `            ``st2.append(root2)` `            ``root2 ``=` `root2.right`   `        ``# If either gets empty then corresponding` `        ``# tree traversal is completed` `        ``if` `(``len``(st1) ``or` `len``(st2)):` `            ``break`   `        ``top1 ``=` `st1[``len``(st1) ``-` `1``]` `        ``top2 ``=` `st2[``len``(st2) ``-` `1``]`   `        ``# If the sum of the node's is equal to 'x'` `        ``if` `((top1.data ``+` `top2.data) ``=``=` `x):` `            `  `            ``# Increment count` `            ``count ``+``=` `1`   `            ``# Pop nodes from the respective stacks` `            ``st1.remove(st1[``len``(st1) ``-` `1``])` `            ``st2.remove(st2[``len``(st2) ``-` `1``])`   `            ``# Insert next possible node in the` `            ``# respective stacks` `            ``root1 ``=` `top1.right` `            ``root2 ``=` `top2.left`   `        ``# Move to next possible node in the` `        ``# inorder traversal of BST 1` `        ``elif` `((top1.data ``+` `top2.data) < x):` `            ``st1.remove(st1[``len``(st1) ``-` `1``])` `            ``root1 ``=` `top1.right`   `        ``# Move to next possible node in the` `        ``# reverse inorder traversal of BST 2` `        ``else``:` `            ``st2.remove(st2[``len``(st2) ``-` `1``])` `            ``root2 ``=` `top2.left`   `    ``# Required count of pairs` `    ``return` `count`   `# Driver code` `if` `__name__ ``=``=` `'__main__'``:` `    `  `    ``# Formation of BST 1` `    ``'''      5` `           ``/   \  ` `          ``3     7 ` `         ``/ \   / \ ` `        ``2   4 6   8` `    ``'''` `    ``root1 ``=` `getNode(``5``)  ` `    ``root1.left ``=` `getNode(``3``)` `    ``root1.right ``=` `getNode(``7``) ` `    ``root1.left.left ``=` `getNode(``2``)` `    ``root1.left.right ``=` `getNode(``4``)` `    ``root1.right.left ``=` `getNode(``6``)` `    ``root1.right.right ``=` `getNode(``8``)`   `    ``# Formation of BST 2` `    ``'''    10  ` `         ``/   \` `        ``6     15 ` `       ``/ \   /  \  ` `      ``3  8  11  18 ` `    ``'''` `    ``root2 ``=` `getNode(``10``) ` `    ``root2.left ``=` `getNode(``6``) ` `    ``root2.right ``=` `getNode(``15``)` `    ``root2.left.left ``=` `getNode(``3``) ` `    ``root2.left.right ``=` `getNode(``8``) ` `    ``root2.right.left ``=` `getNode(``11``)` `    ``root2.right.right ``=` `getNode(``18``)`   `    ``x ``=` `16` `    `  `    ``print``(``"Pairs = "``, countPairs(root1, root2, x))`   `# This code is contributed by bgangwar59`

## C#

 `// C# implementation to count pairs from two` `// BSTs whose sum is equal to a given  value x` `using` `System;` `using` `System.Collections.Generic;`   `// C# implementation to count pairs from two ` `// BSTs whose sum is equal to a given  value x ` `public` `class` `GFG` `{`   `    ``// structure of a node of BST ` `    ``public` `class` `Node` `    ``{` `        ``public` `int` `data;` `        ``public` `Node left, right;`   `        ``// constructor ` `        ``public` `Node(``int` `data)` `        ``{` `            ``this``.data = data;` `            ``left = ``null``;` `            ``right = ``null``;` `        ``}` `    ``}`   `    ``public` `static` `Node root1;` `    ``public` `static` `Node root2;` `    ``// function to count pairs from two BSTs ` `    ``// whose sum is equal to a given value x ` `    ``public` `static` `int` `countPairs(Node root1, Node root2, ``int` `x)` `    ``{` `        ``// if either of the tree is empty ` `        ``if` `(root1 == ``null` `|| root2 == ``null``)` `        ``{` `            ``return` `0;` `        ``}`   `        ``// stack 'st1' used for the inorder ` `        ``// traversal of BST 1 ` `        ``// stack 'st2' used for the reverse ` `        ``// inorder traversal of BST 2 ` `        ``//stack st1, st2; ` `        ``Stack st1 = ``new` `Stack();` `        ``Stack st2 = ``new` `Stack();` `        ``Node top1, top2;`   `        ``int` `count = 0;`   `        ``// the loop will break when either of two ` `        ``// traversals gets completed ` `        ``while` `(``true``)` `        ``{`   `            ``// to find next node in inorder ` `            ``// traversal of BST 1 ` `            ``while` `(root1 != ``null``)` `            ``{` `                ``st1.Push(root1);` `                ``root1 = root1.left;` `            ``}`   `            ``// to find next node in reverse ` `            ``// inorder traversal of BST 2 ` `            ``while` `(root2 != ``null``)` `            ``{` `                ``st2.Push(root2);` `                ``root2 = root2.right;` `            ``}`   `            ``// if either gets empty then corresponding ` `            ``// tree traversal is completed ` `            ``if` `(st1.Count == 0 || st2.Count == 0)` `            ``{` `                ``break``;` `            ``}`   `            ``top1 = st1.Peek();` `            ``top2 = st2.Peek();`   `            ``// if the sum of the node's is equal to 'x' ` `            ``if` `((top1.data + top2.data) == x)` `            ``{` `                ``// increment count ` `                ``count++;`   `                ``// pop nodes from the respective stacks ` `                ``st1.Pop();` `                ``st2.Pop();`   `                ``// insert next possible node in the ` `                ``// respective stacks ` `                ``root1 = top1.right;` `                ``root2 = top2.left;` `            ``}`   `            ``// move to next possible node in the ` `            ``// inorder traversal of BST 1 ` `            ``else` `if` `((top1.data + top2.data) < x)` `            ``{` `                ``st1.Pop();` `                ``root1 = top1.right;` `            ``}`   `            ``// move to next possible node in the ` `            ``// reverse inorder traversal of BST 2 ` `            ``else` `            ``{` `                ``st2.Pop();` `                ``root2 = top2.left;` `            ``}` `        ``}`   `        ``// required count of pairs ` `        ``return` `count;` `    ``}`   `    ``// Driver program to test above ` `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``// formation of BST 1 ` `        ``root1 = ``new` `Node(5); ``//             5` `        ``root1.left = ``new` `Node(3); ``//           /   \` `        ``root1.right = ``new` `Node(7); ``//         3     7` `        ``root1.left.left = ``new` `Node(2); ``//    / \   / \` `        ``root1.left.right = ``new` `Node(4); ``//  2   4 6   8` `        ``root1.right.left = ``new` `Node(6);` `        ``root1.right.right = ``new` `Node(8);`   `        ``// formation of BST 2 ` `        ``root2 = ``new` `Node(10); ``//           10` `        ``root2.left = ``new` `Node(6); ``//           /   \` `        ``root2.right = ``new` `Node(15); ``//        6     15` `        ``root2.left.left = ``new` `Node(3); ``//    / \   /  \` `        ``root2.left.right = ``new` `Node(8); ``//  3  8  11  18` `        ``root2.right.left = ``new` `Node(11);` `        ``root2.right.right = ``new` `Node(18);`   `        ``int` `x = 16;` `        ``Console.WriteLine(``"Pairs = "` `+ countPairs(root1, root2, x));` `    ``}` `}`   `  ``// This code is contributed by Shrikant13`

## Javascript

 ``

Output

`Pairs = 3`

Time Complexity: O(n1 + n2)
Auxiliary Space: O(h1 + h2), Where h1 is height of first tree and h2 is height of second tree

Method 3 :

1. Recursive approach to solving this question.
2. Traverse the BST1 and for each node find the diff i.e. (x – root1.data) in BST2 and increment the count.

Implementation:

## C++

 `// C++ implementation to count pairs from two` `// BSTs whose sum is equal to a given  value x` `#include ` `using` `namespace` `std;`   `// structure of a node of BST` `struct` `Node {` `    ``int` `data;` `    ``Node *left, *right;`   `    ``// constructor` `    ``Node(``int` `data)` `    ``{` `        ``this``->data = data;` `        ``left = NULL;` `        ``right = NULL;` `    ``}` `};`   `static` `int` `pairCount = 0;`   `void` `findPairs(Node* root2, ``int` `diff)` `{` `    ``if` `(root2 == NULL) {` `        ``return``;` `    ``}` `    ``if` `(diff > root2->data) {` `        ``findPairs(root2->right, diff);` `    ``}` `    ``else` `{` `        ``findPairs(root2->left, diff);` `    ``}` `    ``if` `(root2->data == diff) {` `        ``pairCount++;` `    ``}` `}`   `void` `traverseTree(Node* root1, Node* root2, ``int` `sum)` `{` `    ``if` `(root1 == NULL || root2 == NULL) {` `        ``return``;` `    ``}` `    ``traverseTree(root1->left, root2, sum);` `    ``traverseTree(root1->right, root2, sum);` `    ``int` `diff = sum - root1->data;` `    ``findPairs(root2, diff);` `}`   `// function to count pairs from two BSTs` `// whose sum is equal to a given value x` `int` `countPairs(Node* root1, Node* root2, ``int` `sum)` `{` `    ``traverseTree(root1, root2, sum);` `    ``return` `pairCount;` `}`   `// Driver program to test above` `int` `main()` `{` `    ``// formation of BST 1` `    ``Node* root1 = ``new` `Node(5); ``/*             5        */` `    ``root1->left = ``new` `Node(3); ``/*           /   \      */` `    ``root1->right = ``new` `Node(7); ``/*         3     7     */` `    ``root1->left->left = ``new` `Node(2); ``/*    / \   / \    */` `    ``root1->left->right = ``new` `Node(4); ``/*  2   4 6   8 */` `    ``root1->right->left = ``new` `Node(6);` `    ``root1->right->right = ``new` `Node(8);`   `    ``// formation of BST 2` `    ``Node* root2 = ``new` `Node(10); ``/*           10         */` `    ``root2->left = ``new` `Node(6); ``/*           /   \ */` `    ``root2->right = ``new` `Node(15); ``/*        6     15 */` `    ``root2->left->left = ``new` `Node(3); ``/*    / \   /  \ */` `    ``root2->left->right = ``new` `Node(8); ``/*  3  8  11  18    */` `    ``root2->right->left = ``new` `Node(11);` `    ``root2->right->right = ``new` `Node(18);`   `    ``int` `x = 16;` `    ``cout << ``"Pairs = "` `<< countPairs(root1, root2, x);` `}`   `// This code is contributed by Tapesh (tapeshdua420)`

## Java

 `// Java implementation to count pairs from two` `// BSTs whose sum is equal to a given  value x` `import` `java.util.Stack;` `public` `class` `GFG {`   `    ``// structure of a node of BST` `    ``static` `class` `Node {` `        ``int` `data;` `        ``Node left, right;`   `        ``// constructor` `        ``public` `Node(``int` `data)` `        ``{` `            ``this``.data = data;` `            ``left = ``null``;` `            ``right = ``null``;` `        ``}` `    ``}`   `    ``static` `Node root1;` `    ``static` `Node root2;` `  `  `    ``// function to count pairs from two BSTs` `    ``// whose sum is equal to a given value x` `    ``public` `static` `int` `pairCount = ``0``;` `    ``public` `static` `void` `traverseTree(Node root1, Node root2,` `                                    ``int` `sum)` `    ``{` `        ``if` `(root1 == ``null` `|| root2 == ``null``) {` `            ``return``;` `        ``}` `        ``traverseTree(root1.left, root2, sum);` `        ``traverseTree(root1.right, root2, sum);` `        ``int` `diff = sum - root1.data;` `        ``findPairs(root2, diff);` `    ``}`   `    ``private` `static` `void` `findPairs(Node root2, ``int` `diff)` `    ``{` `        ``if` `(root2 == ``null``) {` `            ``return``;` `        ``}` `        ``if` `(diff > root2.data) {` `            ``findPairs(root2.right, diff);` `        ``}` `        ``else` `{` `            ``findPairs(root2.left, diff);` `        ``}` `        ``if` `(root2.data == diff) {` `            ``pairCount++;` `        ``}` `    ``}`   `    ``public` `static` `int` `countPairs(Node root1, Node root2,` `                                 ``int` `sum)` `    ``{` `        ``traverseTree(root1, root2, sum);` `        ``return` `pairCount;` `    ``}`   `    ``// Driver program to test above` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``// formation of BST 1` `        ``root1 = ``new` `Node(``5``); ``/*             5        */` `        ``root1.left = ``new` `Node(``3``); ``/*           /   \      */` `        ``root1.right = ``new` `Node(``7``); ``/*         3     7     */` `        ``root1.left.left = ``new` `Node(``2``); ``/*    / \   / \    */` `        ``root1.left.right = ``new` `Node(``4``); ``/*  2   4 6   8 */` `        ``root1.right.left = ``new` `Node(``6``);` `        ``root1.right.right = ``new` `Node(``8``);`   `        ``// formation of BST 2` `        ``root2 = ``new` `Node(``10``); ``/*           10         */` `        ``root2.left = ``new` `Node(``6``); ``/*           /   \ */` `        ``root2.right = ``new` `Node(``15``); ``/*        6     15 */` `        ``root2.left.left = ``new` `Node(``3``); ``/*    / \   /  \ */` `        ``root2.left.right` `            ``= ``new` `Node(``8``); ``/*  3  8  11  18    */` `        ``root2.right.left = ``new` `Node(``11``);` `        ``root2.right.right = ``new` `Node(``18``);`   `        ``int` `x = ``16``;` `        ``System.out.println(``"Pairs = "` `                           ``+ countPairs(root1, root2, x));` `    ``}` `}` `// This code is contributed by Sujit Panda`

## Python3

 `# Python implementation to count pairs from two` `# BSTs whose sum is equal to a given  value x`   `# structure of a node of BST` `class` `Node:` `    `  `    ``# constructor` `    ``def` `__init__(``self``,data):` `        ``self``.data ``=` `data` `        ``self``.left ``=` `None` `        ``self``.right ``=` `None`   `root1,root2 ``=` `None``,``None` `  `  `# def to count pairs from two BSTs` `# whose sum is equal to a given value x` `pairCount ``=` `0` `def` `traverseTree(root1,  root2, ``sum``):`   `    ``if` `(root1 ``=``=` `None` `or` `root2 ``=``=` `None``):` `        ``return` `    ``traverseTree(root1.left, root2, ``sum``)` `    ``traverseTree(root1.right, root2, ``sum``)` `    ``diff ``=` `sum` `-` `root1.data` `    ``findPairs(root2, diff)`   `def` `findPairs(root2 , diff):`   `    ``global` `pairCount` `    `  `    ``if` `(root2 ``=``=` `None``):` `        ``return`   `    ``if` `(diff > root2.data) :` `        ``findPairs(root2.right, diff)` `    ``else` `:` `        ``findPairs(root2.left, diff)` `    ``if` `(root2.data ``=``=` `diff):` `        ``pairCount ``+``=` `1`   `def` `countPairs(root1, root2, ``sum``):` `    ``global` `pairCount`   `    ``traverseTree(root1, root2, ``sum``)` `    ``return` `pairCount`   `# Driver program to test above`   `# formation of BST 1` `root1 ``=` `Node(``5``)      ` `root1.left ``=` `Node(``3``)   ` `root1.right ``=` `Node(``7``)` `root1.left.left ``=` `Node(``2``) ` `root1.left.right ``=` `Node(``4``)   ` `root1.right.left ``=` `Node(``6``)` `root1.right.right ``=` `Node(``8``)`   `# formation of BST 2` `root2 ``=` `Node(``10``)    ` `root2.left ``=` `Node(``6``)    ` `root2.right ``=` `Node(``15``)` `root2.left.left ``=` `Node(``3``)` `root2.left.right ``=` `Node(``8``)   ` `root2.right.left ``=` `Node(``11``)` `root2.right.right ``=` `Node(``18``)`   `x ``=` `16` `print``(f``"Pairs = {countPairs(root1, root2, x)}"``)`   `# This code is contributed by shinjanpatra`

## C#

 `// C# implementation to count pairs from two` `// BSTs whose sum is equal to a given  value x` `using` `System;`   `using` `System.Collections.Generic;` `public` `class` `GFG {`   `    ``// structure of a node of BST` `    ``public` `class` `Node {` `        ``public` `int` `data;` `        ``public` `Node left, right;`   `        ``// constructor` `        ``public` `Node(``int` `data)` `        ``{` `            ``this``.data = data;` `            ``left = ``null``;` `            ``right = ``null``;` `        ``}` `    ``}`   `    ``static` `Node root1;` `    ``static` `Node root2;` `  `  `    ``// function to count pairs from two BSTs` `    ``// whose sum is equal to a given value x` `    ``public` `static` `int` `pairCount = 0;` `    ``public` `static` `void` `traverseTree(Node root1, Node root2,` `                                    ``int` `sum)` `    ``{` `        ``if` `(root1 == ``null` `|| root2 == ``null``) {` `            ``return``;` `        ``}` `        ``traverseTree(root1.left, root2, sum);` `        ``traverseTree(root1.right, root2, sum);` `        ``int` `diff = sum - root1.data;` `        ``findPairs(root2, diff);` `    ``}`   `    ``private` `static` `void` `findPairs(Node root2, ``int` `diff)` `    ``{` `        ``if` `(root2 == ``null``) {` `            ``return``;` `        ``}` `        ``if` `(diff > root2.data) {` `            ``findPairs(root2.right, diff);` `        ``}` `        ``else` `{` `            ``findPairs(root2.left, diff);` `        ``}` `        ``if` `(root2.data == diff) {` `            ``pairCount++;` `        ``}` `    ``}`   `    ``public` `static` `int` `countPairs(Node root1, Node root2,` `                                 ``int` `sum)` `    ``{` `        ``traverseTree(root1, root2, sum);` `        ``return` `pairCount;` `    ``}`   `    ``// Driver program to test above` `    ``public` `static` `void` `Main(String []args)` `    ``{` `        ``// formation of BST 1` `        ``root1 = ``new` `Node(5); ``/*             5        */` `        ``root1.left = ``new` `Node(3); ``/*           /   \      */` `        ``root1.right = ``new` `Node(7); ``/*         3     7     */` `        ``root1.left.left = ``new` `Node(2); ``/*    / \   / \    */` `        ``root1.left.right = ``new` `Node(4); ``/*  2   4 6   8 */` `        ``root1.right.left = ``new` `Node(6);` `        ``root1.right.right = ``new` `Node(8);`   `        ``// formation of BST 2` `        ``root2 = ``new` `Node(10); ``/*           10         */` `        ``root2.left = ``new` `Node(6); ``/*           /   \ */` `        ``root2.right = ``new` `Node(15); ``/*        6     15 */` `        ``root2.left.left = ``new` `Node(3); ``/*    / \   /  \ */` `        ``root2.left.right` `            ``= ``new` `Node(8); ``/*  3  8  11  18    */` `        ``root2.right.left = ``new` `Node(11);` `        ``root2.right.right = ``new` `Node(18);`   `        ``int` `x = 16;` `        ``Console.WriteLine(``"Pairs = "` `                           ``+ countPairs(root1, root2, x));` `    ``}` `}`   `// This code is contributed by Rajput-Ji`

## Javascript

 ``

Output

`Pairs = 3`

Time Complexity: O(n1 * n2), As for every node in the BST1 we need to traverse the BST2 and check if it is equal to diff or not.
Auxiliary Space: O(h1 + h2), Here h1 is the height of BST1 and h2 is the height of the BST2.

Method 4 : Using BinarySearch Tree Iterator ( A more general way of doing this )

Create two class one as BSTIterator1 and other as BSTIterator2. These two class corresponds to inOrder and reverse inOrder traversal respectively.

Each class will have three methods:

• hasNext : will return true when traversal is not yet completed
• next : will move the pointer to the next node
• peek : will return current node in the traversal

After creating two such classes, simple run the iterator while both have next node and find the sum. If sum == x, increment the next pointer of iterator1 and iterator2 and if sum > x ,increment the next pointer of iterator2 else increment the next pointer of iterator1 i.e when sum < x.

Implementation:

## C++

 `// C++ Program to Count pairs from two BSTs whose sum is` `// equal to a given value x using BinarySearch Tree Iterator` `#include ` `using` `namespace` `std;`   `class` `Node {` `public``:` `    ``int` `data;` `    ``Node* left;` `    ``Node* right;` `    ``Node(``int` `data)` `    ``{` `        ``this``->data = data;` `        ``this``->left = NULL;` `        ``this``->right = NULL;` `    ``}` `};`   `// inorder successor iterator` `class` `BSTIterator1 {` `public``:` `    ``stack s1;` `    ``Node* root1;` `    ``bool` `hasPeeked = ``false``;` `    ``BSTIterator1(Node* root) { ``this``->root1 = root; }` `    ``bool` `hasNext()` `    ``{` `        ``if` `(!s1.empty() || root1 != NULL)` `            ``return` `true``;` `        ``return` `false``;` `    ``}` `    ``Node* peek()` `    ``{` `        ``if` `(!hasNext())` `            ``return` `NULL;` `        ``while` `(root1 != NULL) {` `            ``s1.push(root1);` `            ``root1 = root1->left;` `            ``hasPeeked = ``true``;` `        ``}` `        ``return` `s1.top();` `    ``}` `    ``int` `next()` `    ``{` `        ``if` `(!hasNext())` `            ``return` `-1;` `        ``if` `(!hasPeeked)` `            ``peek();` `        ``hasPeeked = ``false``;` `        ``root1 = s1.top();` `        ``s1.pop();` `        ``Node* temp = root1;` `        ``root1 = root1->right;` `        ``return` `temp->data;` `    ``}` `};`   `// inorder predecessor iterator` `class` `BSTIterator2 {` `public``:` `    ``stack s1;` `    ``Node* root1;` `    ``bool` `hasPeeked = ``false``;` `    ``BSTIterator2(Node* root) { ``this``->root1 = root; }` `    ``bool` `hasNext()` `    ``{` `        ``if` `(!s1.empty() || root1 != NULL)` `            ``return` `true``;` `        ``return` `false``;` `    ``}` `    ``Node* peek()` `    ``{` `        ``if` `(!hasNext())` `            ``return` `NULL;` `        ``while` `(root1 != NULL) {` `            ``s1.push(root1);` `            ``root1 = root1->right;` `            ``hasPeeked = ``true``;` `        ``}` `        ``return` `s1.top();` `    ``}` `    ``int` `next()` `    ``{` `        ``if` `(!hasNext())` `            ``return` `-1;` `        ``if` `(!hasPeeked)` `            ``peek();` `        ``hasPeeked = ``false``;` `        ``root1 = s1.top();` `        ``s1.pop();` `        ``Node* temp = root1;` `        ``root1 = root1->left;` `        ``return` `temp->data;` `    ``}` `};`   `int` `countPairs(Node* r1, Node* r2, ``int` `x)` `{`   `    ``BSTIterator1* it1 = ``new` `BSTIterator1(r1);` `    ``BSTIterator2* it2 = ``new` `BSTIterator2(r2);` `    ``int` `count = 0;` `    ``while` `(it1->hasNext() && it2->hasNext()) {` `        ``Node* n1 = it1->peek();` `        ``Node* n2 = it2->peek();` `        ``int` `sum = n1->data + n2->data;` `        ``if` `(sum == x) {` `            ``count++;` `            ``it1->next();` `            ``it2->next();` `        ``}` `        ``else` `if` `(sum > x) {` `            ``it2->next();` `        ``}` `        ``else` `{` `            ``it1->next();` `        ``}` `    ``}` `    ``return` `count;` `}`   `// Driver program to test above` `int` `main()` `{` `    ``Node *root1, *root2;` `    ``// formation of BST 1` `    ``root1 = ``new` `Node(5); ``/*                     5        */` `    ``root1->left = ``new` `Node(3); ``/*           /   \      */` `    ``root1->right = ``new` `Node(7); ``/*         3     7     */` `    ``root1->left->left = ``new` `Node(2); ``/*    / \   / \    */` `    ``root1->left->right = ``new` `Node(4); ``/*  2   4 6   8   */` `    ``root1->right->left = ``new` `Node(6);` `    ``root1->right->right = ``new` `Node(8);`   `    ``// formation of BST 2` `    ``root2 = ``new` `Node(10); ``/*                   10      */` `    ``root2->left = ``new` `Node(6); ``/*           /   \    */` `    ``root2->right = ``new` `Node(15); ``/*        6     15  */` `    ``root2->left->left = ``new` `Node(3); ``/*    / \   /  \ */` `    ``root2->left->right = ``new` `Node(8); ``/*  3  8  11  18    */` `    ``root2->right->left = ``new` `Node(11);` `    ``root2->right->right = ``new` `Node(18);`   `    ``int` `x = 16;` `    ``cout << ``"Pairs = "` `<< countPairs(root1, root2, x)` `         ``<< endl;` `}`   `// This code is contributed by Tapesh (tapeshdua420)`

## Java

 `import` `java.util.*;` `class` `Node{` `    ``int` `data;` `      ``Node left, right;` `       ``public` `Node(``int` `data){` `        ``this``.data = data;` `          ``this``.left = ``null``;` `          ``this``.right = ``null``;` `    ``}` `}` `// inorder successor iterator` `class` `BSTIterator1{` `    ``Stack s1 = ``new` `Stack<>();` `    ``Node root1;` `    ``boolean` `hasPeeked = ``false``;` `    ``public` `BSTIterator1(Node root){` `        ``this``.root1 = root;` `    ``}` `    ``public` `boolean` `hasNext(){` `        ``if``(!s1.isEmpty() || root1!=``null``)` `            ``return` `true``;` `        ``return` `false``;` `    ``}` `    ``public` `Node peek(){` `        ``if``(!hasNext())` `            ``return` `null``;` `        ``while``(root1!=``null``){` `            ``s1.push(root1);` `            ``root1 = root1.left;` `            ``hasPeeked = ``true``;` `        ``}` `        ``return` `s1.peek();` `    ``}` `    ``public` `int` `next(){` `        ``if``(!hasNext())` `            ``return` `-``1``;` `        ``if``(!hasPeeked)` `            ``peek();` `        ``hasPeeked = ``false``;` `        ``root1 = s1.pop();` `        ``Node temp = root1;` `        ``root1 = root1.right;` `        ``return` `temp.data;` `    ``}` `}` `// inorder predecessor iterator` `class` `BSTIterator2{` `    ``Stack s1 = ``new` `Stack<>();` `    ``Node root1;` `    ``boolean` `hasPeeked = ``false``;` `    ``public` `BSTIterator2(Node root){` `        ``this``.root1 = root;` `    ``}` `    ``public` `boolean` `hasNext(){` `        ``if``(!s1.isEmpty() || root1!=``null``)` `            ``return` `true``;` `        ``return` `false``;` `    ``}` `    ``public` `Node peek(){` `        ``if``(!hasNext())` `            ``return` `null``;` `        ``while``(root1!=``null``){` `            ``s1.push(root1);` `            ``root1 = root1.right;` `            ``hasPeeked = ``true``;` `        ``}` `        ``return` `s1.peek();` `    ``}` `    ``public` `int` `next(){` `        ``if``(!hasNext())` `            ``return` `-``1``;` `        ``if``(!hasPeeked)` `            ``peek();` `        ``hasPeeked = ``false``;` `        ``root1 = s1.pop();` `        ``Node temp = root1;` `        ``root1 = root1.left;` `        ``return` `temp.data;` `    ``}` `}` `class` `GfG` `{   ` `    ``public` `static` `int` `countPairs(Node r1, Node r2, ``int` `x)` `    ``{` `        `  `        ``BSTIterator1 it1 = ``new` `BSTIterator1(r1);` `        ``BSTIterator2 it2 = ``new` `BSTIterator2(r2);` `        ``int` `count = ``0``;` `        ``while``(it1.hasNext() && it2.hasNext()){` `            ``Node n1 = it1.peek();` `            ``Node n2 = it2.peek();` `            ``int` `sum = n1.data+n2.data;` `            ``if``(sum == x){` `                ``count++;` `                ``it1.next();` `                ``it2.next();` `            ``}` `            ``else` `if``(sum > x){` `                ``it2.next();` `            ``}``else``{` `                ``it1.next();` `            ``}` `        ``}` `        ``return` `count;` `        `  `    ``}` `   ``// Driver program to test above` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``Node root1, root2;` `          ``// formation of BST 1` `        ``root1 = ``new` `Node(``5``); ``/*                     5        */` `        ``root1.left = ``new` `Node(``3``); ``/*           /   \      */` `        ``root1.right = ``new` `Node(``7``); ``/*         3     7     */` `        ``root1.left.left = ``new` `Node(``2``); ``/*    / \   / \    */` `        ``root1.left.right = ``new` `Node(``4``); ``/*  2   4 6   8   */` `        ``root1.right.left = ``new` `Node(``6``);` `        ``root1.right.right = ``new` `Node(``8``);`   `        ``// formation of BST 2` `        ``root2 = ``new` `Node(``10``); ``/*                   10      */` `        ``root2.left = ``new` `Node(``6``); ``/*           /   \    */` `        ``root2.right = ``new` `Node(``15``); ``/*        6     15  */` `        ``root2.left.left = ``new` `Node(``3``); ``/*    / \   /  \ */` `        ``root2.left.right` `            ``= ``new` `Node(``8``); ``/*  3  8  11  18    */` `        ``root2.right.left = ``new` `Node(``11``);` `        ``root2.right.right = ``new` `Node(``18``);`   `        ``int` `x = ``16``;` `        ``System.out.println(``"Pairs = "` `                           ``+ countPairs(root1, root2, x));` `    ``}` `}`

## Python3

 `class` `Node:` `    ``data ``=` `0` `    ``left ``=` `None` `    ``right ``=` `None`   `    ``def` `__init__(``self``, data):` `        ``self``.data ``=` `data` `        ``self``.left ``=` `None` `        ``self``.right ``=` `None` `        `  `# inorder successor iterator` `class` `BSTIterator1:` `    ``s1 ``=` `[]` `    ``root1 ``=` `None` `    ``hasPeeked ``=` `False`   `    ``def` `__init__(``self``, root):` `        ``self``.root1 ``=` `root`   `    ``def` `hasNext(``self``):` `        ``if` `(``not` `(``len``(``self``.s1) ``=``=` `0``) ``or` `self``.root1 !``=` `None``):` `            ``return` `True` `        ``return` `False`   `    ``def` `peek(``self``):` `        ``if` `(``not` `self``.hasNext()):` `            ``return` `None` `        ``while` `(``self``.root1 !``=` `None``):` `            ``self``.s1.append(``self``.root1)` `            ``self``.root1 ``=` `self``.root1.left` `            ``self``.hasPeeked ``=` `True` `        ``return` `self``.s1[``-``1``]`   `    ``def` `next``(``self``):` `        ``if` `(``not` `self``.hasNext()):` `            ``return` `-``1` `        ``if` `(``not` `self``.hasPeeked):` `            ``self``.peek()` `        ``self``.hasPeeked ``=` `False` `        ``self``.root1 ``=` `self``.s1.pop()` `        ``temp ``=` `self``.root1` `        ``self``.root1 ``=` `self``.root1.right` `        ``return` `temp.data` `      `  `# inorder predecessor iterator` `class` `BSTIterator2:` `    ``s1 ``=` `[]` `    ``root1 ``=` `None` `    ``hasPeeked ``=` `False`   `    ``def` `__init__(``self``, root):` `        ``self``.root1 ``=` `root`   `    ``def` `hasNext(``self``):` `        ``if` `(``not` `(``len``(``self``.s1) ``=``=` `0``) ``or` `self``.root1 !``=` `None``):` `            ``return` `True` `        ``return` `False`   `    ``def` `peek(``self``):` `        ``if` `(``not` `self``.hasNext()):` `            ``return` `None` `        ``while` `(``self``.root1 !``=` `None``):` `            ``self``.s1.append(``self``.root1)` `            ``self``.root1 ``=` `self``.root1.right` `            ``self``.hasPeeked ``=` `True` `        ``return` `self``.s1[``-``1``]`   `    ``def` `next``(``self``):` `        ``if` `(``not` `self``.hasNext()):` `            ``return` `-``1` `        ``if` `(``not` `self``.hasPeeked):` `            ``self``.peek()` `        ``self``.hasPeeked ``=` `False` `        ``self``.root1 ``=` `self``.s1.pop()` `        ``temp ``=` `self``.root1` `        ``self``.root1 ``=` `self``.root1.left` `        ``return` `temp.data`   `class` `GfG:` `    ``@staticmethod` `    ``def` `countPairs(r1,  r2,  x):` `        ``it1 ``=` `BSTIterator1(r1)` `        ``it2 ``=` `BSTIterator2(r2)` `        ``count ``=` `0` `        ``while` `(it1.hasNext() ``and` `it2.hasNext()):` `            ``n1 ``=` `it1.peek()` `            ``n2 ``=` `it2.peek()` `            ``sum` `=` `n1.data ``+` `n2.data` `            ``if` `(``sum` `=``=` `x):` `                ``count ``+``=` `1` `                ``it1.``next``()` `                ``it2.``next``()` `            ``elif``(``sum` `> x):` `                ``it2.``next``()` `            ``else``:` `                ``it1.``next``()` `        ``return` `count` `      `  `    ``# Driver program to test above` `    ``@staticmethod` `    ``def` `main(args):` `        ``root1 ``=` `None` `        ``root2 ``=` `None` `        `  `        ``# formation of BST 1` `        ``root1 ``=` `Node(``5``)` `        ``#                     5` `        ``root1.left ``=` `Node(``3``)` `        ``#           /   \` `        ``root1.right ``=` `Node(``7``)` `        ``#         3     7` `        ``root1.left.left ``=` `Node(``2``)` `        ``#    / \   / \` `        ``root1.left.right ``=` `Node(``4``)` `        ``#  2   4 6   8` `        ``root1.right.left ``=` `Node(``6``)` `        ``root1.right.right ``=` `Node(``8``)` `        ``# formation of BST 2` `        ``root2 ``=` `Node(``10``)` `        ``#                   10` `        ``root2.left ``=` `Node(``6``)` `        ``#           /   \` `        ``root2.right ``=` `Node(``15``)` `        ``#        6     15` `        ``root2.left.left ``=` `Node(``3``)` `        ``#    / \   /  \` `        ``root2.left.right ``=` `Node(``8``)` `        ``#  3  8  11  18` `        ``root2.right.left ``=` `Node(``11``)` `        ``root2.right.right ``=` `Node(``18``)` `        ``x ``=` `16` `        ``print``(``"Pairs = "` `+` `str``(GfG.countPairs(root1, root2, x)))`   `if` `__name__ ``=``=` `"__main__"``:` `    ``GfG.main([])`   `# This code is contributed by mukulsomukesh`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `public` `class` `Node{` `  ``public` `int` `data;` `  ``public` `Node left, right;` `  ``public` `Node(``int` `data){` `    ``this``.data = data;` `    ``this``.left = ``null``;` `    ``this``.right = ``null``;` `  ``}` `}`   `// inorder successor iterator` `public` `class` `BSTIterator1{` `  ``public` `Stack s1 = ``new` `Stack();` `  ``public` `Node root1;` `  ``public` `bool` `hasPeeked = ``false``;` `  ``public` `BSTIterator1(Node root){` `    ``this``.root1 = root;` `  ``}` `  ``public` `bool` `hasNext(){` `    ``if``(s1.Count != 0 || root1 != ``null``)` `      ``return` `true``;` `    ``return` `false``;` `  ``}` `  ``public` `Node peek(){` `    ``if``(!hasNext())` `      ``return` `null``;` `    ``while``(root1 != ``null``){` `      ``s1.Push(root1);` `      ``root1 = root1.left;` `      ``hasPeeked = ``true``;` `    ``}` `    ``return` `s1.Peek();` `  ``}` `  ``public` `int` `next(){` `    ``if``(!hasNext())` `      ``return` `-1;` `    ``if``(!hasPeeked)` `      ``peek();` `    ``hasPeeked = ``false``;` `    ``root1 = s1.Pop();` `    ``Node temp = root1;` `    ``root1 = root1.right;` `    ``return` `temp.data;` `  ``}` `}` `// inorder predecessor iterator` `public` `class` `BSTIterator2{` `  ``public` `Stack s1 = ``new` `Stack();` `  ``public` `Node root1;` `  ``public` `bool` `hasPeeked = ``false``;` `  ``public` `BSTIterator2(Node root){` `    ``this``.root1 = root;` `  ``}` `  ``public` `bool` `hasNext(){` `    ``if``(s1.Count != 0 || root1 != ``null``)` `      ``return` `true``;` `    ``return` `false``;` `  ``}` `  ``public` `Node peek(){` `    ``if``(!hasNext())` `      ``return` `null``;` `    ``while``(root1 != ``null``){` `      ``s1.Push(root1);` `      ``root1 = root1.right;` `      ``hasPeeked = ``true``;` `    ``}` `    ``return` `s1.Peek();` `  ``}` `  ``public` `int` `next(){` `    ``if``(!hasNext())` `      ``return` `-1;` `    ``if``(!hasPeeked)` `      ``peek();` `    ``hasPeeked = ``false``;` `    ``root1 = s1.Pop();` `    ``Node temp = root1;` `    ``root1 = root1.left;` `    ``return` `temp.data;` `  ``}` `}` `public` `class` `GfG` `{   ` `  ``public` `static` `int` `countPairs(Node r1, Node r2, ``int` `x)` `  ``{`   `    ``BSTIterator1 it1 = ``new` `BSTIterator1(r1);` `    ``BSTIterator2 it2 = ``new` `BSTIterator2(r2);` `    ``int` `count = 0;` `    ``while``(it1.hasNext() && it2.hasNext()){` `      ``Node n1 = it1.peek();` `      ``Node n2 = it2.peek();` `      ``int` `sum = n1.data+n2.data;` `      ``if``(sum == x){` `        ``count++;` `        ``it1.next();` `        ``it2.next();` `      ``}` `      ``else` `if``(sum > x){` `        ``it2.next();` `      ``}``else``{` `        ``it1.next();` `      ``}` `    ``}` `    ``return` `count;`   `  ``}` `  `  `  ``// Driver program to test above` `  ``public` `static` `void` `Main(String []args)` `  ``{` `    ``Node root1, root2;` `    `  `    ``// formation of BST 1` `    ``root1 = ``new` `Node(5); ``/*                     5        */` `    ``root1.left = ``new` `Node(3); ``/*           /   \      */` `    ``root1.right = ``new` `Node(7); ``/*         3     7     */` `    ``root1.left.left = ``new` `Node(2); ``/*    / \   / \    */` `    ``root1.left.right = ``new` `Node(4); ``/*  2   4 6   8   */` `    ``root1.right.left = ``new` `Node(6);` `    ``root1.right.right = ``new` `Node(8);`   `    ``// formation of BST 2` `    ``root2 = ``new` `Node(10); ``/*                   10      */` `    ``root2.left = ``new` `Node(6); ``/*           /   \    */` `    ``root2.right = ``new` `Node(15); ``/*        6     15  */` `    ``root2.left.left = ``new` `Node(3); ``/*    / \   /  \ */` `    ``root2.left.right` `      ``= ``new` `Node(8); ``/*  3  8  11  18    */` `    ``root2.right.left = ``new` `Node(11);` `    ``root2.right.right = ``new` `Node(18);`   `    ``int` `x = 16;` `    ``Console.WriteLine(``"Pairs = "` `                      ``+ countPairs(root1, root2, x));` `  ``}` `}`   `// This code is contributed by Rajput-Ji `

## Javascript

 `class Node {` `    ``constructor(data) {` `        ``this``.data = data;` `        ``this``.left = ``null``;` `        ``this``.right = ``null``;` `    ``}` `}`   `class BSTIterator1 {` `    ``constructor(root) {` `        ``this``.s1 = [];` `        ``this``.root1 = root;` `        ``this``.hasPeeked = ``false``;` `    ``}`   `    ``hasNext() {` `        ``if` `(``this``.s1.length === 0 && ``this``.root1 === ``null``) {` `            ``return` `false``;` `        ``}` `        ``return` `true``;` `    ``}`   `    ``peek() {` `        ``if` `(!``this``.hasNext()) {` `            ``return` `null``;` `        ``}` `        ``while` `(``this``.root1 !== ``null``) {` `            ``this``.s1.push(``this``.root1);` `            ``this``.root1 = ``this``.root1.left;` `            ``this``.hasPeeked = ``true``;` `        ``}` `        ``return` `this``.s1[``this``.s1.length - 1];` `    ``}`   `    ``next() {` `        ``if` `(!``this``.hasNext()) {` `            ``return` `-1;` `        ``}` `        ``if` `(!``this``.hasPeeked) {` `            ``this``.peek();` `        ``}` `        ``this``.hasPeeked = ``false``;` `        ``let temp = ``this``.s1.pop();` `        ``this``.root1 = temp.right;` `        ``return` `temp.data;` `    ``}` `}`   `class BSTIterator2 {` `    ``constructor(root) {` `        ``this``.s1 = [];` `        ``this``.root1 = root;` `        ``this``.hasPeeked = ``false``;` `    ``}`   `    ``hasNext() {` `        ``if` `(``this``.s1.length === 0 && ``this``.root1 === ``null``) {` `            ``return` `false``;` `        ``}` `        ``return` `true``;` `    ``}`   `    ``peek() {` `        ``if` `(!``this``.hasNext()) {` `            ``return` `null``;` `        ``}` `        ``while` `(``this``.root1 !== ``null``) {` `            ``this``.s1.push(``this``.root1);` `            ``this``.root1 = ``this``.root1.right;` `            ``this``.hasPeeked = ``true``;` `        ``}` `        ``return` `this``.s1[``this``.s1.length - 1];` `    ``}`   `    ``next() {` `        ``if` `(!``this``.hasNext()) {` `            ``return` `-1;` `        ``}` `        ``if` `(!``this``.hasPeeked) {` `            ``this``.peek();` `        ``}` `        ``this``.hasPeeked = ``false``;` `        ``let temp = ``this``.s1.pop();` `        ``this``.root1 = temp.left;` `        ``return` `temp.data;` `    ``}` `}`   `class GfG {` `    ``static countPairs(r1, r2, x) {` `        ``let it1 = ``new` `BSTIterator1(r1);` `        ``let it2 = ``new` `BSTIterator2(r2);` `        ``let count = 0;` `        ``while` `(it1.hasNext() && it2.hasNext()) {` `        ``let n1 = it1.peek();` `        ``let n2 = it2.peek();` `        ``let sum = n1.data + n2.data;` `        ``if` `(sum == x) {` `           ``count++;` `           ``it1.next();` `           ``it2.next();` `        ``} ``else` `if` `(sum > x) {` `            ``it2.next();` `            ``} ``else` `{` `           ``it1.next();` `        ``}` `       ``}` `       ``return` `count;` `    ``}` `        ``}`   `// Driver program to test above function` `let root1 = ``null``;` `let root2 = ``null``;`   `// formation of BST 1` `root1 = ``new` `Node(5);` `// 5` `root1.left = ``new` `Node(3);` `// /` `root1.right = ``new` `Node(7);` `// 3 7` `root1.left.left = ``new` `Node(2);` `root1.left.right = ``new` `Node(4);` `// 2 4 6 8` `root1.right.left = ``new` `Node(6);` `root1.right.right = ``new` `Node(8);`   `// formation of BST 2` `root2 = ``new` `Node(10);` `// 10` `root2.left = ``new` `Node(6);` `// /` `root2.right = ``new` `Node(15);` `// 6 15` `root2.left.left = ``new` `Node(3);` `root2.left.right = ``new` `Node(8);` `console.log(GfG.countPairs(root1, root2, 10));`

Output

`Pairs = 3`

Time Complexity: O(n1 + n2)
Auxiliary Space: O(h1 + h2), Where h1 is height of first tree and h2 is height of second tree

Previous
Next