Count pairs in a binary tree whose sum is equal to a given value x

Given a binary tree containing n distinct numbers and a value x. The problem is to count pairs in the given binary tree whose sum is equal to the given value x.

Examples:

Input : 
        5      
       / \      
      3   7      
     / \ / \  
    2  4 6  8   

        x = 10

Output : 3
The pairs are (3, 7), (2, 8) and (4, 6).

1) Naive Approach: One by one get each node of the binary tree through any of the tree traversals method. Pass the node say temp, the root of the tree and value x to another function say findPair(). In the function with the help of the root pointer traverse the tree again. One by one sum up these nodes with temp and check whether sum == x. If so, increment count. Calculate count = count / 2 as a single pair has been counted twice by the aforementioned method.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to count pairs in a binary tree
// whose sum is equal to given value x
#include <bits/stdc++.h>
using namespace std;
  
// structure of a node of a binary tree
struct Node {
    int data;
    Node *left, *right;
};
  
// function to create and return a node
// of a binary tree
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;
}
  
// returns true if a pair exists with given sum 'x'
bool findPair(Node* root, Node* temp, int x)
{
    // base case
    if (!root)
        return false;
  
    // pair exists
    if (root != temp && ((root->data + temp->data) == x))
        return true;
  
    // find pair in left and right subtress
    if (findPair(root->left, temp, x) || findPair(root->right, temp, x))
        return true;
  
    // pair does not exists with given sum 'x'
    return false;
}
  
// function to count pairs in a binary tree
// whose sum is equal to given value x
void countPairs(Node* root, Node* curr, int x, int& count)
{
    // if tree is empty
    if (!curr)
        return;
  
    // check whether pair exists for current node 'curr'
    // in the binary tree that sum up to 'x'
    if (findPair(root, curr, x))
        count++;
  
    // recursively count pairs in left subtree
    countPairs(root, curr->left, x, count);
  
    // recursively count pairs in right subtree
    countPairs(root, curr->right, x, count);
}
  
// Driver program to test above
int main()
{
    // formation of binary tree
    Node* root = getNode(5); /*        5      */
    root->left = getNode(3); /*       / \      */
    root->right = getNode(7); /*    3   7      */
    root->left->left = getNode(2); /*   / \ / \   */
    root->left->right = getNode(4); /*   2 4 6 8   */
    root->right->left = getNode(6);
    root->right->right = getNode(8);
  
    int x = 10;
    int count = 0;
  
    countPairs(root, root, x, count);
    count = count / 2;
  
    cout << "Count = " << count;
  
    return 0;
}

chevron_right


Output:

Count = 3

Time Complexity: O(n^2).

2) Efficient Approach: Following are the steps:

  1. Convert given binary tree to doubly linked list. Refer this post.
  2. Sort the doubly linked list obtained in Step 1. Refer this post.
  3. Count Pairs in sorted doubly linked with sum equal to ‘x’. Refer this post.
  4. Display the count obtained in Step 4.
filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to count pairs in a binary tree
// whose sum is equal to given value x
#include <bits/stdc++.h>
using namespace std;
  
// structure of a node of a binary tree
struct Node {
    int data;
    Node *left, *right;
};
  
// function to create and return a node
// of a binary tree
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;
}
  
// A simple recursive function to convert a given
// Binary tree to Doubly Linked List
// root     --> Root of Binary Tree
// head_ref --> Pointer to head node of created
// doubly linked list
void BToDLL(Node* root, Node** head_ref)
{
    // Base cases
    if (root == NULL)
        return;
  
    // Recursively convert right subtree
    BToDLL(root->right, head_ref);
  
    // insert root into DLL
    root->right = *head_ref;
  
    // Change left pointer of previous head
    if (*head_ref != NULL)
        (*head_ref)->left = root;
  
    // Change head of Doubly linked list
    *head_ref = root;
  
    // Recursively convert left subtree
    BToDLL(root->left, head_ref);
}
  
// Split a doubly linked list (DLL) into 2 DLLs of
// half sizes
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;
}
  
// Function to merge two sorted doubly linked lists
Node* merge(Node* first, Node* second)
{
    // If first linked list is empty
    if (!first)
        return second;
  
    // If second linked list is empty
    if (!second)
        return first;
  
    // Pick the smaller value
    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;
    }
}
  
// Function to do merge sort
Node* mergeSort(Node* head)
{
    if (!head || !head->right)
        return head;
    Node* second = split(head);
  
    // Recur for left and right halves
    head = mergeSort(head);
    second = mergeSort(second);
  
    // Merge the two sorted halves
    return merge(head, second);
}
  
// Function to count pairs in a sorted doubly linked list
// whose sum equal to given value x
int pairSum(Node* head, int x)
{
    // Set two pointers, first to the beginning of DLL
    // and second to the end of DLL.
    Node* first = head;
    Node* second = head;
    while (second->right != NULL)
        second = second->right;
  
    int count = 0;
  
    // The loop terminates when either of two pointers
    // become NULL, or they cross each other (second->right
    // == first), or they become same (first == second)
    while (first != NULL && second != NULL && first != second && second->right != first) {
        // pair found
        if ((first->data + second->data) == x) {
            count++;
  
            // move first in forward direction
            first = first->right;
  
            // move second in backward direction
            second = second->left;
        }
        else {
            if ((first->data + second->data) < x)
                first = first->right;
            else
                second = second->left;
        }
    }
  
    return count;
}
  
// function to count pairs in a binary tree
// whose sum is equal to given value x
int countPairs(Node* root, int x)
{
    Node* head = NULL;
    int count = 0;
  
    // Convert binary tree to
    // doubly linked list
    BToDLL(root, &head);
  
    // sort DLL
    head = mergeSort(head);
  
    // count pairs
    return pairSum(head, x);
}
  
// Driver program to test above
int main()
{
    // formation of binary tree
    Node* root = getNode(5); /*        5      */
    root->left = getNode(3); /*       / \      */
    root->right = getNode(7); /*    3   7      */
    root->left->left = getNode(2); /*   / \ / \   */
    root->left->right = getNode(4); /*   2 4 6 8   */
    root->right->left = getNode(6);
    root->right->right = getNode(8);
  
    int x = 10;
  
    cout << "Count = "
         << countPairs(root, x);
  
    return 0;
}

chevron_right


Output:

Count = 3

Time Complexity: O(nLog n).

3)Another Efficient Approach – No need for converting to DLL and sorting: Following are the steps:

  1. Traverse the tree in any order (pre / post / in).
  2. Create an empty hash and keep adding difference between current node’s value and X to it.
  3. At each node, check if it’s value is in the hash, if yes then increment the count by 1 and DO NOT add this node’s value’s difference with X in the hash to avoid duplicate counting for a single pair.
filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to Count pairs 
# in a binary tree whose sum is 
# equal to a given value x
  
# Node class to represent a
# node in the binary tree 
# with value, left and right attributes
class Node(object):
    def __init__(self, value, left = None, right = None):
        self.value = value
        self.left = left
        self.right = right
  
# To store count of pairs
count = 0
  
# To store difference between 
# current node's value and x,
# acts a lookup for counting pairs
hash_t = set()
  
# The input, we need to count 
# pairs whose sum is equal to x
x = 10
  
# Function to count number of pairs
# Does a pre-order traversal of the tree
def count_pairs_w_sum(root):
    # global count
    if root:
        if root.value in hash_t:
            count += 1
        else:
            hash_t.add(x-root.value)
          
        count_pairs_w_sum(root.left)
        count_pairs_w_sum(root.right)
  
# Entry point / Driver - Create a 
# binary tree and call the function 
# to get the count
if __name__ == '__main__':
    root = Node(5)
      
    root.left = Node(3)
    root.right = Node(7)
      
    root.left.left = Node(2)
    root.left.right = Node(4)
      
    root.right.left = Node(6)
    root.right.right = Node(8)
      
    count_pairs_w_sum(root)
      
    print count

chevron_right


Output:

Count = 3

Time Complexity: O(n)
Space Complexity: O(n)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Vijayant Soni