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 tree has more nodes?
Analyze the time complexity of the following code snippet.
public bool FindTarget(TreeNode root, int k) {
var set = new HashSet<int>();
return Dfs(root, k, set);
}
private bool Dfs(TreeNode node, int k, HashSet<int> set) {
if (node == null) return false;
if (set.Contains(k - node.val)) return true;
set.Add(node.val);
return Dfs(node.left, k, set) || Dfs(node.right, k, set);
}
This code searches the tree to find if two values add up to the target by checking each node once and storing seen values.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive traversal of each node in the tree.
- How many times: Each node is visited exactly once during the depth-first search.
As the number of nodes grows, the function visits each node once, so the work grows directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits and checks |
| 100 | About 100 visits and checks |
| 1000 | About 1000 visits and checks |
Pattern observation: The operations increase in a straight line as the tree size increases.
Time Complexity: O(n)
This means the time to find the two sum grows directly with the number of nodes in the tree.
[X] Wrong: "Because the tree is a BST, we can find the pair in less than linear time by skipping nodes."
[OK] Correct: The algorithm must check each node to be sure, so it still visits all nodes once, making it linear time.
Understanding this helps you explain how searching in trees works and shows you can analyze recursive code clearly.
"What if we used an in-order traversal to get 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 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 if such a pair exists, not to find max, count nodes, or check balance.Final Answer:
Find two nodes in the BST whose values add up to a target sum. -> Option AQuick Check:
Two Sum in BST = Find pair with target sum [OK]
- Confusing with finding max or min value
- Thinking it counts nodes instead of finding pairs
- Assuming it checks tree balance
Solution
Step 1: Understand the expected return type
The function should return true or false depending on whether two nodes sum to the target, so return type must bebool.Step 2: Check method signature options
bool FindTarget(TreeNode root, int target) returnsbool, matching the requirement. Others returnint,void, orstring, which are incorrect for this purpose.Final Answer:
bool FindTarget(TreeNode root, int target) -> Option BQuick Check:
Return type bool for true/false check [OK]
- Using void return type and expecting a result
- Returning int or string instead of bool
- Incorrect parameter types
FindTarget return?
5
/ \
3 6
/ \ \
2 4 7
Solution
Step 1: Identify pairs that sum to target 9
Check pairs: 2+7=9, 3+6=9, 4+5=9. All these pairs exist in the BST.Step 2: Confirm function behavior
Since at least one pair (e.g., 2 and 7) sums to 9, the function should return true.Final Answer:
true -> Option DQuick Check:
Pair exists with sum 9 = true [OK]
- Ignoring valid pairs in BST
- Assuming no pair without checking all nodes
- Confusing output with null or error
FindTarget in a BST:
public bool FindTarget(TreeNode root, int k) {
HashSet<int> set = new HashSet<int>();
return DFS(root, k, set);
}
private bool DFS(TreeNode node, int k, HashSet<int> set) {
if (node == null) return false;
if (set.Contains(k - node.val)) return true;
set.Add(node.val);
DFS(node.left, k, set);
DFS(node.right, k, set);
return false;
}
What is the main bug causing incorrect results?Solution
Step 1: Analyze DFS recursive calls
The DFS calls to left and right subtrees are made but their return values are ignored.Step 2: Understand impact on return value
Because the recursive calls' results are not returned or checked, the function always returns false unless the first node matches.Step 3: Correct fix
Return the result of DFS calls combined with OR logic to propagate true upwards.Final Answer:
DFS calls do not return their results, so always returns false. -> Option CQuick Check:
Missing return in recursion causes false always [OK]
- Ignoring return values of recursive calls
- Incorrect base case return value
- Unnecessary data structure misuse
Solution
Step 1: Analyze each approach's efficiency
Approach A uses O(n) space and O(n) time for traversal plus O(n) for two pointers. Approach B uses O(n) space but only one traversal with O(n) time. Approach C is O(n^2) time, inefficient. Approach D is unclear and inefficient.Step 2: Choose the most efficient method
Using a HashSet during DFS (Approach B) is efficient in time and space, as it checks complements on the fly without extra traversal.Final Answer:
Use HashSet during DFS to check complements. -> Option AQuick Check:
HashSet during DFS = efficient O(n) time and space [OK]
- Choosing double traversal with two pointers over HashSet
- Trying all pairs causing O(n^2) time
- Using queues unnecessarily increasing complexity
Ready to prove it?
Pass the test and this pattern moves unknown
