Two Sum in BST in DSA Python - 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 number of steps change when the BST has more nodes?
Analyze the time complexity of the following code snippet.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_target(root, k):
seen = set()
def dfs(node):
if not node:
return False
if k - node.val in seen:
return True
seen.add(node.val)
return dfs(node.left) or dfs(node.right)
return dfs(root)
This code checks if there are two numbers in the BST that add up to k by walking through the tree once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive depth-first search (DFS) visiting each node once.
- How many times: Once per node, so n times for n nodes.
As the tree grows, the function visits each node once, so the steps grow directly with the number of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 visits |
| 100 | About 100 visits |
| 1000 | About 1000 visits |
Pattern observation: The number of steps grows in a straight line with the number of nodes.
Time Complexity: O(n)
This means the time to find the two numbers grows directly with the size of the tree.
[X] Wrong: "Because the tree is sorted, we only need to check a few nodes, so it's faster than O(n)."
[OK] Correct: The code visits every node to be sure, so it still takes time proportional to all nodes.
Understanding how to analyze recursive tree searches helps you explain your approach clearly and shows you know how your code scales.
"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 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 find if such a pair exists, not to find max value, check balance, or count nodes.Final Answer:
Find two nodes in a BST whose values add up to a target sum -> Option AQuick Check:
Two Sum in BST means find pair with sum = target [OK]
- Confusing with finding max/min value
- Thinking it checks BST balance
- Assuming it counts nodes
Solution
Step 1: Identify correct set initialization syntax
In Python,set()creates an empty set. Using[]creates a list,{}creates an empty dictionary, and()creates an empty tuple.Step 2: Confirm usage for visited nodes
We need a set to quickly check if a complement value exists, sovisited = set()is correct.Final Answer:
visited = set() -> Option BQuick Check:
Empty set = set() [OK]
- Using [] which creates a list, not a set
- Using {} which creates a dict, not a set
- Using () which creates a tuple
find_target(root, 9) return?BST structure:
5
/ \
3 6
/ \ \
2 4 7
Code snippet:
def find_target(root, k):
visited = set()
def dfs(node):
if not node:
return False
if k - node.val in visited:
return True
visited.add(node.val)
return dfs(node.left) or dfs(node.right)
return dfs(root)Solution
Step 1: Trace DFS traversal and visited set updates
Start at root 5: visited = {}. Check if 9-5=4 in visited? No. Add 5.
Go left to 3: check 9-3=6 in visited? No. Add 3.
Go left to 2: check 9-2=7 in visited? No. Add 2.
Left and right of 2 are None, return False.
Back to 3, go right to 4: check 9-4=5 in visited? Yes (5 is in visited). Return True.Step 2: Confirm function returns True
Since a pair (5,4) sums to 9, function returns True.Final Answer:
True -> Option AQuick Check:
Pair (5,4) found = True [OK]
- Not updating visited set before recursive calls
- Returning False too early
- Confusing node values and complements
def find_target(root, k):
visited = set()
def dfs(node):
if not node:
return False
if node.val in visited:
return True
visited.add(k - node.val)
return dfs(node.left) or dfs(node.right)
return dfs(root)Solution
Step 1: Understand the logic for Two Sum in BST
We must check if the complement (k - current node value) exists in visited set. If yes, return True. Then add current node value to visited.Step 2: Identify the bug in code
The code incorrectly checks if node.val is in visited and adds (k - node.val) to visited. This reverses the logic and causes wrong results.Step 3: Correct fix
Check if (k - node.val) in visited, then add node.val to visited.Final Answer:
Check if (k - node.val) in visited, add node.val to visited -> Option DQuick Check:
Check complement in visited, add current value [OK]
- Swapping check and add values
- Adding complement instead of current value
- Checking current value instead of complement
Solution
Step 1: Analyze each approach
Use DFS with a hash set to check complements during traversal: O(n) time and O(n) space.
Use inorder traversal to get sorted list, then use two pointers to find sum: O(n) time and O(n) space.
Check every pair of nodes by nested traversal (O(n²)): inefficient.
Convert BST to a max heap and search pairs: unnecessary and costly.Step 2: Choose the most efficient approach
Both DFS with hash set and inorder + two pointers have O(n) time and space, but DFS with hash set uses less extra space by checking on the fly during traversal, avoiding full list creation.Final Answer:
Use DFS with a hash set to check complements during traversal -> Option CQuick Check:
DFS + hash set = efficient Two Sum in BST [OK]
- Choosing nested loops causing O(n²) time
- Ignoring space complexity of inorder list
- Unnecessary BST conversions
Ready to prove it?
Pass the test and this pattern moves unknown
