Two Sum in BST in DSA C++ - Time & Space Complexity
We want to know how the time needed to find two numbers that add up to a target grows as the tree gets bigger.
How does the search time change when the number of nodes in the BST increases?
Analyze the time complexity of the following code snippet.
bool findTarget(TreeNode* root, int k) {
unordered_set<int> seen;
return dfs(root, k, seen);
}
bool dfs(TreeNode* node, int k, unordered_set<int>& seen) {
if (!node) return false;
if (seen.count(k - node->val)) return true;
seen.insert(node->val);
return dfs(node->left, k, seen) || dfs(node->right, k, seen);
}
This code searches the BST to find if any two nodes sum to the target value k using a depth-first search and a set to track visited values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each node once in the tree using recursion.
- How many times: Each node is visited exactly one time.
As the number of nodes grows, the function checks each node once, so the work grows directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 node visits |
| 100 | About 100 node visits |
| 1000 | About 1000 node visits |
Pattern observation: The operations increase in a straight line with the number of nodes.
Time Complexity: O(n)
This means the time to find the two sum grows directly with the number of nodes in the BST.
[X] Wrong: "Because the tree is sorted, we can find the two sum in less than linear time like O(log n)."
[OK] Correct: The code visits every node to check pairs, so it still needs to look at all nodes in the worst case.
Understanding how to analyze recursive tree searches helps you explain your approach clearly and shows you know how the algorithm scales with input size.
"What if we used an in-order traversal to create a sorted list first, then used two pointers to find the sum? How would the time complexity change?"
Practice
Two Sum in BST problem?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 BQuick Check:
Two Sum in BST means finding two nodes summing to target [OK]
- Confusing with finding max/min value
- Thinking it counts nodes instead of pairs
- Assuming it checks tree balance
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 CQuick Check:
BST nodes use pointers for children [OK]
- Using objects instead of pointers for children
- Mixing pointer and non-pointer types
- Forgetting semicolon after struct
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;
}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 AQuick Check:
3 + 6 = 9 found in BST [OK]
- Assuming no pair exists without checking all nodes
- Confusing DFS order with BFS
- Ignoring the use of hash set for complements
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;
dfs(node->left);
dfs(node->right);
seen.insert(node->val);
return false;
};
return dfs(root);
}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 AQuick Check:
Insert before recursion to find complements [OK]
- Inserting after recursion causes missed pairs
- Changing return values incorrectly
- Replacing set with vector reduces efficiency
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 DQuick Check:
Handle duplicates by verifying two distinct nodes [OK]
- Ignoring duplicate values causing false positives
- Skipping pairs with same node value
- Switching data structures unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
