using
System;
using
System.Collections.Generic;
class
Node {
public
int
data;
public
Node left;
public
Node right;
public
Node(
int
x)
{
data = x;
left =
null
;
right =
null
;
}
}
class
Program {
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;
}
static
int
countPairs(Node root1, Node root2,
int
x)
{
HashSet<
int
> s =
new
HashSet<
int
>();
Stack<Node> st =
new
Stack<Node>();
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;
}
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;
}
static
void
Main(
string
[] args)
{
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);
int
x = 16;
Console.WriteLine(
"Count of pairs with sum "
+ x
+
" is "
+ countPairs(root1, root2, x));
}
}