Open In App

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 methods. 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.

Implementation:

C++

 // C++ implementation to count pairs in a binary tree// whose sum is equal to given value x#include using namespace std; // structure of a node of a binary treestruct Node {    int data;    Node *left, *right;}; // function to create and return a node// of a binary treeNode* 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;      return new_node;} // 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 subtrees    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 xvoid 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 aboveint 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;}// This code is contributed by yash agarwal(yashagarwal2852002)

Java

 // Java implementation to count pairs in a binary tree// whose sum is equal to given value ximport java.util.*; class GFG{ // structure of a node of a binary treestatic class Node{    int data;    Node left, right;};static int count; // function to create and return a node// of a binary treestatic Node getNode(int data){    // allocate space for the node    Node new_node = new Node();     // put in the data    new_node.data = data;    new_node.left = new_node.right = null;    return new_node;} // returns true if a pair exists with given sum 'x'static boolean findPair(Node root, Node temp, int x){    // base case    if (root==null)        return false;     // pair exists    if (root != temp && ((root.data + temp.data) == x))        return true;     // find pair in left and right subtrees    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 xstatic void countPairs(Node root, Node curr, int x){    // if tree is empty    if (curr == null)        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);     // recursively count pairs in right subtree    countPairs(root, curr.right, x);} // Driver codepublic static void main(String[] args){    // 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;    count = 0;     countPairs(root, root, x);    count = count / 2;     System.out.print("Count = " + count);}} // This code is contributed by PrinciRaj1992

Python3

 # Python3 implementation to count pairs in a binary tree# whose sum is equal to given value x # structure of a node of a binary treeclass getNode(object):    def __init__(self, value):        self.data = value        self.left = None        self.right = None # returns True if a pair exists with given sum 'x'def findPair(root, temp, x):    # base case    if root == None:        return False             # pair exists    if (root != temp and ((root.data + temp.data) == x)):        return True             # find pair in left and right subtrees    if (findPair(root.left, temp, x) or 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 xdef countPairs(root, curr, x):    global count         # if tree is empty    if curr == None:        return         # check whether pair exists for current node 'curr'    # in the binary tree that sum up to 'x'    if (findPair(root, curr, x)):        count += 1             # recursively count pairs in left subtree    countPairs(root, curr.left, x)         # recursively count pairs in right subtree    countPairs(root, curr.right, x) # Driver program to test above# formation of binary treeroot = getNode(5)   root.left = getNode(3)root.right = getNode(7)root.left.left = getNode(2)root.left.right = getNode(4)root.right.left = getNode(6)root.right.right = getNode(8)x = 10count = 0 countPairs(root, root, x)count = count // 2 print("Count =", count) # This code is contributed by shubhamsingh10

C#

 // C# implementation to count pairs in a binary tree// whose sum is equal to given value xusing System; class GFG{ // structure of a node of a binary treeclass Node{    public int data;    public Node left, right;};static int count; // function to create and return a node// of a binary treestatic Node getNode(int data){    // allocate space for the node    Node new_node = new Node();     // put in the data    new_node.data = data;    new_node.left = new_node.right = null;    return new_node;} // returns true if a pair exists with given sum 'x'static bool findPair(Node root, Node temp, int x){    // base case    if (root == null)        return false;     // pair exists    if (root != temp && ((root.data + temp.data) == x))        return true;     // find pair in left and right subtrees    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 xstatic void countPairs(Node root, Node curr, int x){    // if tree is empty    if (curr == null)        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);     // recursively count pairs in right subtree    countPairs(root, curr.right, x);} // Driver codepublic static void Main(String[] args){    // 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;    count = 0;     countPairs(root, root, x);    count = count / 2;     Console.Write("Count = " + count);}} // This code is contributed by Rajput-Ji

Javascript



Output

Count = 3

Time Complexity: O(n^2).

Auxiliary Space: O(1)

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.

Implementation:

Javascript



Output

Count = 3

Time Complexity: O(nLog n).

Auxiliary Space: O(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.

Implementation:

C++

 #include #include using namespace std; // Node class to represent a// node in the binary tree// with value, left and right attributesclass Node {public:    int value;    Node* left;    Node* right;     Node(int value, Node* left = nullptr, Node* right = nullptr) : value(value), left(left), right(right) {}}; // To store count of pairsint count = 0; // To store difference between// current node's value and x,// acts a lookup for counting pairsunordered_set hash_t; // The input, we need to count// pairs whose sum is equal to xint x = 10; // Function to count number of pairs// Does a pre-order traversal of the treevoid count_pairs_w_sum(Node* root) {    if (root != nullptr) {        if (hash_t.count(root->value)) {            count++;        }        else {            hash_t.insert(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 countint 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);     count_pairs_w_sum(root);     cout << count << endl;     return 0;} // This code is contributed by lokeshpotta20.

Java

 // Java program to Count pairs// in a binary tree whose sum is// equal to a given value ximport java.util.HashSet; public class GFG{   // Node class to represent a  // node in the binary tree  // with value, left and right attributes  static class Node {    int value;    Node left, right;    public Node(int value) {      this.value = value;    }  }      // To store count of pairs  static int count = 0;   // To store difference between  // current node's value and x,  // acts a lookup for counting pairs  static HashSet hash_t = new HashSet();   // The input, we need to count  // pairs whose sum is equal to x  static int x = 10;   // Function to count number of pairs  // Does a pre-order traversal of the tree  static void count_pairs_w_sum(Node root) {    if( root != null) {      if (hash_t.contains(root.value))        count += 1;      else        hash_t.add(x-root.value);       count_pairs_w_sum(root.left);      count_pairs_w_sum(root.right);    }  }    //Driver method  public static void main(String[] args) {    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);     count_pairs_w_sum(root);     System.out.println(count);  }} // This code is contributed by Lovely Jain

Python

 # 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 attributesclass Node(object):    def __init__(self, value, left=None, right=None):        self.value = value        self.left = left        self.right = right  # To store count of pairscount = 0 # To store difference between# current node's value and x,# acts a lookup for counting pairshash_t = set() # The input, we need to count# pairs whose sum is equal to xx = 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 countif __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

C#

 // C# program to count pairs in binary tree whose sum is// equal to a given value in x using System;using System.Collections.Generic; public class GFG {     // Node class to represent a    // node in the binary tree    // with value, left and right attributes    class Node {        public int value;        public Node left, right;        public Node(int value) { this.value = value; }    }     // To stsore count of pairs    static int count = 0;     // To store difference between    // current node's value and x,    // acts a lookup for counting pairs    static HashSet hash_t = new HashSet();     // The input, we need to count    // pairs whose sum is equal to x    static int x = 10;     // Function to count number of pairs    // Does a pre-order traversal of the tree    static void count_pairs_w_sum(Node root)    {        if (root != null) {            if (hash_t.Contains(root.value))                count += 1;            else                hash_t.Add(x - root.value);             count_pairs_w_sum(root.left);            count_pairs_w_sum(root.right);        }    }     static public void Main()    {         // Code        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);         count_pairs_w_sum(root);         Console.WriteLine(count);    }} // This code is contributed by lokeshmvs21.

Javascript

 // THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL// JavaScript program to count pairs in binary tree whose sum is// equal to a given value in xclass Node{    constructor(value){        this.value = value;        this.left = null;        this.right = null;    }} // To store count of pairslet count = 0; // To store difference between// current node's value and x,// acts a lookup for counting pairslet hash_t = new Set(); // The input, we need to count// pairs whose sum is equal to xlet x = 10; // Function to count number of pairs// Does a pre-order traversal of the treefunction count_pairs_w_sum(root){    if(root != null){        if(hash_t.has(root.value)){            count++;        }        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 countlet 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); count_pairs_w_sum(root); console.log(count);

Output

3

Complexity Analysis:

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