📖 Scenario: You have a phone contact list stored as a Binary Search Tree (BST). Each node contains a contact's phone number. You want to find if there are two contacts whose phone numbers add up to a specific target number.
🎯 Goal: Build a program that checks if there exist two nodes in the BST whose values sum up to a given target number.
📋 What You'll Learn
Create a BST with given nodes
Set a target sum value
Implement a function to find if two numbers in the BST add up to the target
Print true if such a pair exists, otherwise false
💡 Why This Matters
🌍 Real World
Finding pairs of numbers that add up to a target is useful in financial applications, contact management, and data analysis where quick lookups in sorted data structures like BSTs are needed.
💼 Career
This problem helps prepare for coding interviews and real-world tasks involving tree traversal, hashing, and problem-solving with data structures.
Progress0 / 4 steps
1
Create the BST nodes
Create a class called TreeNode with a constructor that takes val, left, and right. Then create the BST with these exact nodes and structure: root node with value 5, left child with value 3, right child with value 6, left child's left child with value 2, left child's right child with value 4, right child's right child with value 7.
DSA Javascript
Hint
Remember to define the TreeNode class first. Then create the root node with value 5, and add children exactly as described.
2
Set the target sum value
Create a variable called target and set it to the number 9.
DSA Javascript
Hint
Just create a constant named target and assign it the value 9.
3
Implement the two sum check function
Write a function called findTarget that takes root and k as parameters. Use a helper Set called seen to store visited node values. Traverse the BST using a helper function dfs. For each node, check if k - node.val is in seen. If yes, return true. Otherwise, add node.val to seen and continue. Return false if no pair found.
DSA Javascript
Hint
Use a Set to remember values you have seen. For each node, check if the complement (target - current value) is in the Set. Use recursion to visit all nodes.
4
Print the result
Print the result of calling findTarget with root and target.
DSA Javascript
Hint
Use console.log to print the result of findTarget(root, target).
Practice
(1/5)
1. What is the main goal of the Two Sum in BST problem?
easy
A. Find the maximum value in the BST.
B. Find two nodes in the BST whose values add up to a target sum.
C. Count the total number of nodes in the BST.
D. Check if the BST is balanced.
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 value, count nodes, or check balance.
Final Answer:
Find two nodes in the BST whose values add up to a target sum. -> Option B
Quick Check:
Two Sum in BST = Find pair with target sum [OK]
Hint: Look for pairs adding to target in BST nodes [OK]
Common Mistakes:
Confusing with finding max or min value
Thinking it counts nodes instead of pairs
Assuming it checks tree balance
2. Which of the following is the correct way to declare a BST node in JavaScript for the Two Sum problem?
easy
A. function Node(val) { this.val = val; this.left = null; this.right = null; }
B. let Node = (val) => { val = val; left = null; right = null; }
C. class Node { constructor(val) { val = val; left = null; right = null; } }
D. var Node = function(val) { this.value = val; this.left = this.right = undefined; }
Solution
Step 1: Check correct property assignments
function Node(val) { this.val = val; this.left = null; this.right = null; } correctly assigns this.val, this.left, and this.right to initialize a BST node.
Step 2: Identify syntax and property errors in other options
let Node = (val) => { val = val; left = null; right = null; } misses this keyword and uses arrow function incorrectly. class Node { constructor(val) { val = val; left = null; right = null; } } assigns to local variables, not this. var Node = function(val) { this.value = val; this.left = this.right = undefined; } uses this.value instead of this.val and sets children to undefined instead of null.
Final Answer:
function Node(val) { this.val = val; this.left = null; this.right = null; } -> Option A
Quick Check:
Correct node declaration uses this.val and null children [OK]
Hint: Use function with this.val, this.left, this.right = null [OK]
Common Mistakes:
Forgetting 'this' keyword for properties
Using arrow functions for constructor
Assigning children to undefined instead of null
3. Given the BST below and target = 9, what will the function findTarget(root, 9) return?
5
/ \
3 6
/ \ \
2 4 7
Assuming findTarget returns true if two nodes sum to target, else false.
medium
A. true
B. false
C. null
D. undefined
Solution
Step 1: Identify pairs that sum to 9
Check pairs: 2+7=9, 3+6=9, 4+5=9. All these pairs exist in the BST.
Step 2: Confirm function returns true if any pair matches
Since pairs exist, findTarget returns true.
Final Answer:
true -> Option A
Quick Check:
Pairs sum to 9 = true [OK]
Hint: Check pairs adding to target in BST nodes [OK]
Common Mistakes:
Ignoring valid pairs in BST
Assuming function returns node instead of boolean
Confusing null or undefined as return
4. Consider this buggy code snippet for Two Sum in BST:
function findTarget(root, k) {
const set = new Set();
function dfs(node) {
if (!node) return false;
if (set.has(k - node.val)) return true;
set.add(node.val);
dfs(node.left);
dfs(node.right);
}
return dfs(root);
}
What is the main bug causing incorrect results?
medium
A. Using Set instead of Array for storage
B. Checking for k - node.val before adding node.val
C. Missing return statements in recursive calls inside dfs
D. Not handling empty tree case
Solution
Step 1: Analyze recursive calls in dfs
The recursive calls to dfs(node.left) and dfs(node.right) do not return their results, so true found deeper is ignored.
Step 2: Fix by returning recursive calls
Adding return before recursive calls ensures if true is found, it propagates up and final result is correct.
Final Answer:
Missing return statements in recursive calls inside dfs -> Option C
Quick Check:
Return recursive calls to propagate true [OK]
Hint: Always return recursive calls to propagate results [OK]
Common Mistakes:
Not returning recursive call results
Confusing Set usage as bug
Ignoring base case handling
5. You want to optimize the Two Sum in BST problem to use O(h) space, where h is tree height. Which approach is best?
hard
A. Convert BST to a linked list and then find pairs.
B. Store all node values in an array and use a hash set to find pairs.
C. Perform a breadth-first search and check pairs at each level.
D. Use two iterators: one in-order and one reverse in-order traversal simultaneously.
Solution
Step 1: Understand space complexity of approaches
Storing all nodes uses O(n) space. BFS also uses O(n) space. Converting to linked list uses O(n).
Step 2: Use two iterators approach
Using two iterators (one in-order for smallest, one reverse in-order for largest) uses O(h) space, where h is tree height, optimizing space.
Final Answer:
Use two iterators: one in-order and one reverse in-order traversal simultaneously. -> Option D
Quick Check:
Two iterators = O(h) space optimization [OK]
Hint: Use two pointers with in-order and reverse in-order traversal [OK]
Common Mistakes:
Using full array storage increasing space to O(n)
Trying BFS which uses more space
Converting BST to linked list wastes space
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.