BadduCoder


SUBMITTED BY: BadduCoder

DATE: March 5, 2020, 5:09 p.m.

FORMAT: C++

SIZE: 1.5 kB

HITS: 521

  1. // CPP program to find a pair with
  2. // given sum using hashing
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5. struct Node {
  6. int data;
  7. struct Node *left, *right;
  8. };
  9. Node* NewNode(int data)
  10. {
  11. Node* temp = (Node*)malloc(sizeof(Node));
  12. temp->data = data;
  13. temp->left = NULL;
  14. temp->right = NULL;
  15. return temp;
  16. }
  17. Node* insert(Node* root, int key)
  18. {
  19. if (root == NULL)
  20. return NewNode(key);
  21. if (key < root->data)
  22. root->left = insert(root->left, key);
  23. else
  24. root->right = insert(root->right, key);
  25. return root;
  26. }
  27. bool findpairUtil(Node* root, int sum, unordered_set<int> &set)
  28. {
  29. if (root == NULL)
  30. return false;
  31. if (findpairUtil(root->left, sum, set))
  32. return true;
  33. if (set.find(sum - root->data) != set.end()) {
  34. cout << "Pair is found ("
  35. << sum - root->data << ", "
  36. << root->data << ")" << endl;
  37. return true;
  38. }
  39. else
  40. set.insert(root->data);
  41. return findpairUtil(root->right, sum, set);
  42. }
  43. void findPair(Node* root, int sum)
  44. {
  45. unordered_set<int> set;
  46. if (!findpairUtil(root, sum, set))
  47. cout << "Pairs do not exit" << endl;
  48. }
  49. // Driver code
  50. int main()
  51. {
  52. Node* root = NULL;
  53. root = insert(root, 15);
  54. root = insert(root, 10);
  55. root = insert(root, 20);
  56. root = insert(root, 8);
  57. root = insert(root, 12);
  58. root = insert(root, 16);
  59. root = insert(root, 25);
  60. root = insert(root, 10);
  61. int sum = 33;
  62. findPair(root, sum);
  63. return 0;
  64. }

comments powered by Disqus