Two Sum in BST in DSA Java - 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.
public boolean findTarget(TreeNode root, int k) {
Set set = new HashSet<>();
return dfs(root, k, set);
}
private boolean dfs(TreeNode node, int k, Set 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 BST to find if any two nodes sum to the target 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: Once per node, so total visits equal the number of nodes n.
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 visits and checks |
| 100 | About 100 visits and checks |
| 1000 | About 1000 visits and checks |
Pattern observation: The operations grow linearly 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, searching for pairs is faster than visiting all nodes."
[OK] Correct: The code visits every node once to check pairs, so it still needs to look at all nodes in the worst case.
Understanding how to analyze tree traversal time helps you explain your approach clearly and shows you know how your solution scales with input size.
"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 if there exist two nodes in the BST such that their values add up to a given target.Step 2: Identify the goal
The goal is to check for the existence of such a pair, not to find max, balance, or count nodes.Final Answer:
Find two nodes in the BST whose values add up to a target sum. -> Option CQuick Check:
Two Sum in BST means finding two nodes summing to target [OK]
- Confusing Two Sum with finding max value
- Thinking problem is about BST balance
- Counting nodes instead of finding pairs
Solution
Step 1: Understand the return type needed
The function should return true or false if a pair exists, so return type is boolean.Step 2: Check method signatures
public boolean findTarget(TreeNode root, int k) returns boolean and accepts root and target, matching the problem requirements.Final Answer:
public boolean findTarget(TreeNode root, int k) -> Option BQuick Check:
Boolean return for existence check [OK]
- Using void return type instead of boolean
- Returning int instead of boolean
- Returning TreeNode instead of boolean
findTarget(root, 9) be?
5
/ \
3 6
/ \ \
2 4 7
Solution
Step 1: Identify pairs that sum to 9
Check pairs: 2+7=9, 3+6=9, 4+5=9. All valid pairs exist.Step 2: Confirm function returns true if any pair found
Since pairs exist, function returns true.Final Answer:
true -> Option AQuick Check:
Pairs 2+7 or 3+6 sum to 9 [OK]
- Ignoring valid pairs and returning false
- Confusing output with node values
- Assuming null or error without reason
public boolean findTarget(TreeNode root, int k) {
Set<Integer> set = new HashSet<>();
return dfs(root, k, set);
}
private boolean dfs(TreeNode node, int k, Set<Integer> 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
dfs calls itself on left and right but ignores their return values.Step 2: Understand impact of missing returns
Without returning results of recursive calls, function always returns false unless first node matches.Step 3: Correct fix
Return true if either left or right dfs call returns true.Final Answer:
Missing return statements from recursive calls in dfs. -> Option DQuick Check:
Return recursive calls to propagate true [OK]
- Ignoring return values of recursive calls
- Using wrong data structure for lookup
- Not handling null root properly
Solution
Step 1: Understand space complexity of approaches
Storing all nodes uses O(n) space; HashSet also O(n); array conversion O(n).Step 2: Two iterator approach
Using two iterators (in-order and reverse in-order) simulates two pointers with O(h) space.Step 3: Choose best approach
Use two iterators: one in-order and one reverse in-order traversal. uses O(h) space and is optimal for BST Two Sum.Final Answer:
Use two iterators: one in-order and one reverse in-order traversal. -> Option AQuick Check:
Two iterators give O(h) space [OK]
- Using full list storage causing O(n) space
- Relying on HashSet which uses O(n) space
- Ignoring BST properties for optimization
Ready to prove it?
Pass the test and this pattern moves unknown
