#include <bits/stdc++.h>
using
namespace
std;
struct
Node {
int
data;
Node *left, *right;
Node(
int
val){
this
->data = val;
this
->left =
this
->right = NULL;
}
};
void
BToDLL(Node* root, Node** head_ref)
{
if
(root == NULL)
return
;
BToDLL(root->right, head_ref);
root->right = *head_ref;
if
(*head_ref != NULL)
(*head_ref)->left = root;
*head_ref = root;
BToDLL(root->left, head_ref);
}
Node* split(Node* head)
{
Node *fast = head, *slow = head;
while
(fast->right && fast->right->right) {
fast = fast->right->right;
slow = slow->right;
}
Node* temp = slow->right;
slow->right = NULL;
return
temp;
}
Node* merge(Node* first, Node* second)
{
if
(!first)
return
second;
if
(!second)
return
first;
if
(first->data < second->data) {
first->right = merge(first->right, second);
first->right->left = first;
first->left = NULL;
return
first;
}
else
{
second->right = merge(first, second->right);
second->right->left = second;
second->left = NULL;
return
second;
}
}
Node* mergeSort(Node* head)
{
if
(!head || !head->right)
return
head;
Node* second = split(head);
head = mergeSort(head);
second = mergeSort(second);
return
merge(head, second);
}
int
pairSum(Node* head,
int
x)
{
Node* first = head;
Node* second = head;
while
(second->right != NULL)
second = second->right;
int
count = 0;
while
(first != NULL && second != NULL && first != second && second->right != first) {
if
((first->data + second->data) == x) {
count++;
first = first->right;
second = second->left;
}
else
{
if
((first->data + second->data) < x)
first = first->right;
else
second = second->left;
}
}
return
count;
}
int
countPairs(Node* root,
int
x)
{
Node* head = NULL;
int
count = 0;
BToDLL(root, &head);
head = mergeSort(head);
return
pairSum(head, x);
}
int
main()
{
Node* root =
new
Node(5);
root->left =
new
Node(3);
root->right =
new
Node(7);
root->left->left =
new
Node(2);
root->left->right =
new
Node(4);
root->right->left =
new
Node(6);
root->right->right =
new
Node(8);
int
x = 10;
cout <<
"Count = "
<< countPairs(root, x);
return
0;
}