-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwoSumBinarySearchTree.cpp
95 lines (93 loc) · 1.65 KB
/
TwoSumBinarySearchTree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Implemented by Kritagya Kumra
#include <algorithm>
#include <iostream>
#include <stack>
#include <queue>
#include <vector>
using namespace std;
class Node
{
public:
int data;
Node *left;
Node *right;
Node(int d)
{
this->data = d;
this->left = NULL;
this->right = NULL;
}
};
bool search(Node *root, int target)
{
if (root == NULL)
{
return false;
}
if (root->data == target)
{
return true;
}
if (root->data < target)
{
return search(root->right, target);
}
else
{
return search(root->right, target);
}
}
bool twoSumInBST(Node *root, int target)
{
if (root == NULL)
{
return false;
}
if (search(root, target - root->data) == true)
{
return true;
}
bool leftAns = twoSumInBST(root->left, target);
bool rightAns = twoSumInBST(root->right, target);
if (leftAns == true || rightAns == true)
{
return true;
}
return false;
}
Node *insertIntoBST(Node *root, int d)
{
if (root == NULL)
{
root = new Node(d);
return root;
}
if (d < root->data)
{
root->left = insertIntoBST(root->left, d);
}
else
{
root->right = insertIntoBST(root->right, d);
}
return root;
}
void takeInput(Node *&root)
{
int d;
cin >> d;
while (d != -1)
{
root = insertIntoBST(root, d);
cin >> d;
}
}
int main()
{
Node *root = NULL;
cout << "Enter data to create a BST" << endl;
takeInput(root);
cout << endl;
cout << "Two sum pair BST: " << twoSumInBST(root, 25);
}
// Implemented by Kritagya Kumra