📖 Scenario: You are working with a phone book stored as a Binary Search Tree (BST). Each node contains a phone number. You want to find if there are two phone numbers in the BST that add up to a specific target sum.
🎯 Goal: Build a program that creates a BST with given phone numbers, sets a target sum, and checks if any two numbers in the BST add up to that target.
📋 What You'll Learn
Create a BST with the exact phone numbers: 10, 5, 15, 3, 7, 18
Create an integer variable called target with the value 22
Implement a function findTarget that returns true if two numbers in the BST add up to target
Print true or false depending on whether such a pair exists
💡 Why This Matters
🌍 Real World
Finding pairs of numbers that add up to a target is useful in financial applications, phone number analysis, and data validation.
💼 Career
Understanding BSTs and hash sets is important for software engineering roles that involve data structures and algorithm optimization.
Progress0 / 4 steps
1
Create the BST with given phone numbers
Create a BST by defining the TreeNode struct and build the tree with these exact phone numbers inserted in this order: 10, 5, 15, 3, 7, 18. Store the root in a variable called root.
DSA C++
Hint
Define a TreeNode struct with val, left, and right. Use an insert function to add nodes to the BST.
2
Set the target sum
Create an integer variable called target and set it to 22.
DSA C++
Hint
Just create a variable target and assign it the value 22.
3
Implement the function to find two numbers summing to target
Implement a function called findTarget that takes TreeNode* root and int k as parameters and returns true if there exist two elements in the BST such that their sum is equal to k. Use an unordered_set<int> to store visited values. Call this function inside main.
DSA C++
Hint
Use recursion to visit each node. Check if k - root->val is in the set. If yes, return true. Otherwise, add root->val to the set and continue.
4
Print the result
Print the value of the variable result using std::cout. It should print true if two numbers add up to target, otherwise false.
DSA C++
Hint
Use std::cout to print "true" if result is true, otherwise "false".
Practice
(1/5)
1. What is the main goal of the Two Sum in BST problem?
easy
A. Find the maximum value in a BST
B. Find two nodes in a BST whose values add up to a target sum
C. Count the number of nodes in a BST
D. Check if a BST is balanced
Solution
Step 1: Understand the problem statement
The problem asks to find if there exist two nodes in a Binary Search Tree (BST) such that their values add up to a given target sum.
Step 2: Identify the goal
The goal is to check for the existence of such a pair, not to find maximum, count nodes, or check balance.
Final Answer:
Find two nodes in a BST whose values add up to a target sum -> Option B
Quick Check:
Two Sum in BST means finding two nodes summing to target [OK]
Hint: Look for two nodes adding to target in BST [OK]
Common Mistakes:
Confusing with finding max/min value
Thinking it counts nodes instead of pairs
Assuming it checks tree balance
2. Which of the following C++ code snippets correctly declares a BST node structure for the Two Sum problem?
easy
A. struct TreeNode { int val; TreeNode left; TreeNode* right; };
B. struct TreeNode { int val; TreeNode left; TreeNode right; };
C. struct TreeNode { int val; TreeNode* left; TreeNode* right; };
D. struct TreeNode { int val; TreeNode* left; TreeNode right; };
Solution
Step 1: Check pointer usage in struct
In C++, child nodes in a tree are pointers to TreeNode objects, so left and right must be pointers.
Step 2: Validate each option
struct TreeNode { int val; TreeNode* left; TreeNode* right; }; uses TreeNode* for left and right, which is correct. Options A, B, and C incorrectly use TreeNode without pointers for one or both children.
Final Answer:
struct TreeNode { int val; TreeNode* left; TreeNode* right; }; -> Option C
Quick Check:
BST nodes use pointers for children [OK]
Hint: Children in BST nodes are pointers in C++ [OK]
Common Mistakes:
Using objects instead of pointers for children
Mixing pointer and non-pointer types
Forgetting semicolon after struct
3. What is the output of the following code snippet that checks for two sum in BST?
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
bool findTarget(TreeNode* root, int k) {
std::unordered_set<int> seen;
std::function dfs = [&](TreeNode* node) {
if (!node) return false;
if (seen.count(k - node->val)) return true;
seen.insert(node->val);
return dfs(node->left) || dfs(node->right);
};
return dfs(root);
}
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);
bool result = findTarget(root, 9);
std::cout << (result ? "true" : "false") << std::endl;
return 0;
}
medium
A. true
B. false
C. Compilation error
D. Runtime error
Solution
Step 1: Understand the tree and target
The BST has nodes 5,3,6,2,4,7. The target sum is 9.
Step 2: Trace the DFS and set usage
DFS visits nodes and checks if (target - current node value) is in the set. For example, when visiting node 6, it checks if 9-6=3 is in set. Node 3 was visited before, so it returns true.
Final Answer:
true -> Option A
Quick Check:
3 + 6 = 9 found in BST [OK]
Hint: Check if complement exists in visited nodes set [OK]
Common Mistakes:
Assuming no pair exists without checking all nodes
Confusing DFS order with BFS
Ignoring the use of hash set for complements
4. Identify the bug in the following Two Sum in BST code snippet and select the correct fix:
A. Insert node->val before recursive calls to children
B. Remove the unordered_set and use a vector instead
C. Change return false to return true at the end
D. Add a null check after inserting node->val
Solution
Step 1: Analyze the order of operations
The code inserts node->val into the set after recursive calls, so complements are not found when visiting children.
Step 2: Fix the insertion timing
Insert node->val before recursive calls so that children can find complements in the set.
Final Answer:
Insert node->val before recursive calls to children -> Option A
Quick Check:
Insert before recursion to find complements [OK]
Hint: Insert current value before recursion to detect complements [OK]
Common Mistakes:
Inserting after recursion causes missed pairs
Changing return values incorrectly
Replacing set with vector reduces efficiency
5. Given a BST with nodes [10, 5, 15, 3, 7, null, 18], how would you modify the Two Sum in BST algorithm to handle the case where the target sum is twice the value of a single node (e.g., target = 14 and node value = 7)?
hard
A. Only check leaf nodes for pairs
B. Ignore pairs where complement equals current node value
C. Use a sorted array instead of a hash set
D. Check if the complement equals the current node value and ensure the node appears twice
Solution
Step 1: Understand the problem with duplicates
If target is twice a node's value, we must ensure two distinct nodes with that value exist.
Step 2: Modify algorithm to handle duplicates
When complement equals current node value, check if the node appears twice (e.g., by counting occurrences or checking different nodes).
Final Answer:
Check if the complement equals the current node value and ensure the node appears twice -> Option D
Quick Check:
Handle duplicates by verifying two distinct nodes [OK]
Hint: Verify two distinct nodes if complement equals current value [OK]
Common Mistakes:
Ignoring duplicate values causing false positives
Skipping pairs with same node value
Switching data structures unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.