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.
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.
Count = 3
Time Complexity: O(n^2).
2) Efficient Approach: Following are the steps:
- Convert given binary tree to doubly linked list. Refer this post.
- Sort the doubly linked list obtained in Step 1. Refer this post.
- Count Pairs in sorted doubly linked with sum equal to ‘x’. Refer this post.
- Display the count obtained in Step 4.
Count = 3
Time Complexity: O(nLog n).
3)Another Efficient Approach – No need for converting to DLL and sorting: Following are the steps:
- Traverse the tree in any order (pre / post / in).
- Create an empty hash and keep adding difference between current node’s value and X to it.
- 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.
Count = 3
Time Complexity: O(n)
Space Complexity: O(n)
- Count pairs from two arrays having sum equal to K
- Count pairs from two linked lists whose sum is equal to a given value
- Count of index pairs with equal elements in an array
- Count pairs from two linked lists whose product is equal to a given value
- Check if the given binary tree has a sub-tree with equal no of 1's and 0's | Set 2
- Number of pairs with a given sum in a Binary Search Tree
- Count the Number of Binary Search Trees present in a Binary Tree
- Check if the given Binary Tree have a Subtree with equal no of 1's and 0's
- Root to leaf paths having equal lengths in a Binary Tree
- Count all k-sum paths in a Binary Tree
- Count Non-Leaf nodes in a Binary Tree
- Program to count leaf nodes in a binary tree
- Count nodes with two children at level L in a Binary Tree
- Count full nodes in a Binary tree (Iterative and Recursive)
- Count half nodes in a Binary tree (Iterative and Recursive)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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