forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 1
/
find_target_k.cpp
90 lines (79 loc) · 2.14 KB
/
find_target_k.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
/*
* Given a Binary Search Tree and a target number,
* return true if there exist two elements in the BST such that their sum is equal to the given target.
*
* Input:
* 5
* / \
* 3 6
* / \ \
* 2 4 7
*
* Target = 9
* Output: True
*
* Target = 28
* Output: False
*
* Approach:
*
* Use a set to insert node values as we traverse the tree. If we find a node such that
* k-current_node_val exist already in set, it means we have found a pair of nodes whose values adds up to k.
* (i.e. current node and node with value k-current_node_val)
*/
#include <iostream>
#include <unordered_set>
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int d): data{d}, left{nullptr}, right{nullptr}{}
};
bool find_target_k(TreeNode* root, int k, std::unordered_set<int>& set)
{
if (root == nullptr) {
return false;
}
if (set.find(k - root->data) != set.end()) {
return true;
}
set.insert(root->data);
return find_target_k(root->left, k, set) ||
find_target_k(root->right, k, set);
}
bool find_target_k(TreeNode* root, int k)
{
std::unordered_set<int> set;
return find_target_k(root, k, set);
}
void print_inorder(TreeNode* root)
{
if (root != nullptr) {
print_inorder(root->left);
std::cout << root->data << " ";
print_inorder(root->right);
}
}
int main()
{
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(3);
root->right = new TreeNode(6);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(4);
root->right->right = new TreeNode(7);
std::cout << "Inorder traversal of the current tree:";
print_inorder(root);
std::cout << std::endl;
if (find_target_k(root, 9)) {
std::cout << "The tree contains two nodes which adds up to 9\n";
} else {
std::cout << "The tree does not contain two nodes which adds up to 9\n";
}
if (find_target_k(root, 24)) {
std::cout << "The tree contains two nodes which adds up to 24\n";
} else {
std::cout << "The tree does not contain two nodes which adds up to 24\n";
}
return 0;
}