Bird
Raised Fist0
DSA Javaprogramming~20 mins

Two Sum in BST in DSA Java - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Two Sum in BST Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Two Sum in BST with target 9
Given the BST below and target = 9, what is the output of the Two Sum function that returns true if two nodes sum to the target?
DSA Java
class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    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);
        return dfs(node.left, k, set) || dfs(node.right, k, set);
    }
}

// BST:
//       5
//      / \
//     3   6
//    / \   \
//   2   4   7
Atrue
Bfalse
Cnull
DCompilation error
Attempts:
2 left
💡 Hint
Check if any two nodes add up to 9.
❓ Predict Output
intermediate
2:00remaining
Output of Two Sum in BST with target 28
Given the same BST as before and target = 28, what is the output of the Two Sum function?
DSA Java
class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    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);
        return dfs(node.left, k, set) || dfs(node.right, k, set);
    }
}

// BST:
//       5
//      / \
//     3   6
//    / \   \
//   2   4   7
ARuntime error
Bnull
Ctrue
Dfalse
Attempts:
2 left
💡 Hint
No two nodes sum to 28.
🔧 Debug
advanced
2:00remaining
Identify the error in Two Sum BST code
What error does the following code produce when run on a BST with target 10?
DSA Java
class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int x) { val = x; }
}

public class Solution {
    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;
    }
}
AAlways returns false
BStackOverflowError
CNullPointerException
DCompilation error
Attempts:
2 left
💡 Hint
Check the return statements in recursion.
🧠 Conceptual
advanced
2:00remaining
Why use a HashSet in Two Sum BST?
Why is a HashSet used in the Two Sum in BST algorithm instead of just searching the BST for complements?
AHashSet reduces memory usage compared to BST search
BHashSet stores nodes in sorted order to help find pairs quickly
CHashSet provides O(1) average lookup time, making the algorithm faster than searching BST repeatedly
DHashSet automatically balances the BST during traversal
Attempts:
2 left
💡 Hint
Think about lookup times.
🚀 Application
expert
3:00remaining
Number of pairs summing to target in BST
Given the BST below and target = 7, how many unique pairs of nodes sum to 7?
DSA Java
// BST:
//       4
//      / \
//     2   6
//    / \ / \
//   1  3 5  7
A1
B3
C4
D2
Attempts:
2 left
💡 Hint
Find all pairs (a,b) where a + b = 7 and a < b.

Practice

(1/5)
1. What is the main goal of the Two Sum in BST problem?
easy
A. Count the total number of nodes in the BST.
B. Find the maximum value in the BST.
C. Find two nodes in the BST whose values add up to a target sum.
D. Check if the BST is balanced.

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Find two nodes in the BST whose values add up to a target sum. -> Option C
  4. Quick Check:

    Two Sum in BST means finding two nodes summing to target [OK]
Hint: Remember Two Sum means pair sums to target [OK]
Common Mistakes:
  • Confusing Two Sum with finding max value
  • Thinking problem is about BST balance
  • Counting nodes instead of finding pairs
2. Which of the following Java method signatures correctly represents a function to solve Two Sum in BST?
easy
A. public int findSum(TreeNode root, int k)
B. public boolean findTarget(TreeNode root, int k)
C. public void findTarget(TreeNode root, int k)
D. public TreeNode findPair(TreeNode root, int k)

Solution

  1. Step 1: Understand the return type needed

    The function should return true or false if a pair exists, so return type is boolean.
  2. Step 2: Check method signatures

    public boolean findTarget(TreeNode root, int k) returns boolean and accepts root and target, matching the problem requirements.
  3. Final Answer:

    public boolean findTarget(TreeNode root, int k) -> Option B
  4. Quick Check:

    Boolean return for existence check [OK]
Hint: Two Sum returns true/false, so use boolean return [OK]
Common Mistakes:
  • Using void return type instead of boolean
  • Returning int instead of boolean
  • Returning TreeNode instead of boolean
3. Given the BST below and target = 9, what will the output of findTarget(root, 9) be?

      5
     / \
    3   6
   / \   \
  2   4   7
medium
A. true
B. false
C. null
D. Runtime Error

Solution

  1. Step 1: Identify pairs that sum to 9

    Check pairs: 2+7=9, 3+6=9, 4+5=9. All valid pairs exist.
  2. Step 2: Confirm function returns true if any pair found

    Since pairs exist, function returns true.
  3. Final Answer:

    true -> Option A
  4. Quick Check:

    Pairs 2+7 or 3+6 sum to 9 [OK]
Hint: Check pairs adding to target in BST nodes [OK]
Common Mistakes:
  • Ignoring valid pairs and returning false
  • Confusing output with node values
  • Assuming null or error without reason
4. Consider this buggy code snippet for Two Sum in BST:

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?
medium
A. Using HashSet instead of ArrayList.
B. Adding node values after checking set.
C. Not checking if root is null in findTarget.
D. Missing return statements from recursive calls in dfs.

Solution

  1. Step 1: Analyze dfs recursive calls

    dfs calls itself on left and right but ignores their return values.
  2. Step 2: Understand impact of missing returns

    Without returning results of recursive calls, function always returns false unless first node matches.
  3. Step 3: Correct fix

    Return true if either left or right dfs call returns true.
  4. Final Answer:

    Missing return statements from recursive calls in dfs. -> Option D
  5. Quick Check:

    Return recursive calls to propagate true [OK]
Hint: Always return recursive call results in DFS [OK]
Common Mistakes:
  • Ignoring return values of recursive calls
  • Using wrong data structure for lookup
  • Not handling null root properly
5. You want to optimize Two Sum in BST to use O(h) space, where h is tree height. Which approach is best?
hard
A. Use two iterators: one in-order and one reverse in-order traversal.
B. Store all node values in a list and use two pointers.
C. Use a HashSet to store visited nodes during DFS.
D. Convert BST to sorted array and binary search for complements.

Solution

  1. Step 1: Understand space complexity of approaches

    Storing all nodes uses O(n) space; HashSet also O(n); array conversion O(n).
  2. Step 2: Two iterator approach

    Using two iterators (in-order and reverse in-order) simulates two pointers with O(h) space.
  3. 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.
  4. Final Answer:

    Use two iterators: one in-order and one reverse in-order traversal. -> Option A
  5. Quick Check:

    Two iterators give O(h) space [OK]
Hint: Two pointers in BST use two iterators for O(h) space [OK]
Common Mistakes:
  • Using full list storage causing O(n) space
  • Relying on HashSet which uses O(n) space
  • Ignoring BST properties for optimization
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard