Bird
Raised Fist0
DSA C++programming~10 mins

Two Sum in BST in DSA C++ - Execution Trace

Choose your learning style10 modes available
Concept Flow - Two Sum in BST
Start at root
↓
Inorder traversal to get sorted array
↓
Initialize two pointers: left=0, right=end
↓
Check sum = arr[left
↓
Return True
↓
Repeat until left >= right
↓
Return False if no pair found
First, we get all BST values in sorted order using inorder traversal. Then, we use two pointers from start and end to find if any two numbers sum to the target.
Execution Sample
DSA C++
void inorder(TreeNode* root, vector<int>& nums) {
  if (!root) return;
  inorder(root->left, nums);
  nums.push_back(root->val);
  inorder(root->right, nums);
}

bool findTarget(TreeNode* root, int k) {
  vector<int> nums;
  inorder(root, nums);
  int left = 0, right = nums.size() - 1;
  while (left < right) {
    int sum = nums[left] + nums[right];
    if (sum == k) return true;
    else if (sum < k) left++;
    else right--;
  }
  return false;
}
This code finds if two numbers in BST sum to k by inorder traversal and two-pointer search.
Execution Table
StepOperationNodes Visited / Array StatePointers (left, right)Sum CheckedActionVisual State
1Inorder traversal startVisited: [] / Array: []--Traverse left subtreeBST nodes visited: 4,2,5,1,3; Array after traversal: [1,2,3,4,5]
2Inorder traversal completeVisited all nodes / Array: [1,2,3,4,5]--Prepare two pointersArray ready: [1,2,3,4,5]
3Initialize pointers[1,2,3,4,5]left=0, right=4-Calculate sumPointers at values 1 and 5
4Check sum[1,2,3,4,5]left=0, right=41+5=66 < 7, move left++left moves to index 1 (value 2)
5Check sum[1,2,3,4,5]left=1, right=42+5=77 == 7, pair foundReturn True
6End[1,2,3,4,5]--Stop searchResult: True
💡 Sum found at step 5 with values 2 and 5 equal to target 7
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 5Final
nums[][1,2,3,4,5][1,2,3,4,5][1,2,3,4,5][1,2,3,4,5]
left-011-
right-444-
sum--67-
Key Moments - 3 Insights
Why do we do an inorder traversal first?
Inorder traversal visits BST nodes in sorted order, which lets us use two pointers efficiently to find the sum. See execution_table step 1 and 2 where array is built.
Why move left pointer when sum is less than target?
Because the array is sorted, increasing left pointer moves to a bigger number, increasing sum. See execution_table step 4 where sum=6 < 7, so left moves from 0 to 1.
Why stop when left >= right?
Because left and right pointers crossing means all pairs checked. No pair found means return false. See concept_flow and execution_table step 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the sum checked at step 4?
A7
B6
C5
D8
💡 Hint
Check the 'Sum Checked' column at step 4 in execution_table
At which step does the algorithm find the pair that sums to the target?
AStep 3
BStep 4
CStep 5
DStep 6
💡 Hint
Look at the 'Action' column for when sum == target in execution_table
If the target was 10 instead of 7, what would happen to the pointers after step 4?
ALeft pointer moves right
BRight pointer moves left
CBoth pointers stay the same
DAlgorithm stops immediately
💡 Hint
Recall that if sum < target, left pointer moves right as per execution_table step 4
Concept Snapshot
Two Sum in BST:
- Use inorder traversal to get sorted array of BST values
- Use two pointers (left at start, right at end)
- Check sum = arr[left] + arr[right]
- If sum == target, return true
- If sum < target, move left pointer right
- If sum > target, move right pointer left
- Stop when pointers cross, return false
Full Transcript
To find if two numbers in a BST sum to a target, first do an inorder traversal to get a sorted list of values. Then use two pointers at the start and end of this list. Check the sum of values at these pointers. If the sum equals the target, return true. If the sum is less than the target, move the left pointer right to increase sum. If the sum is greater, move the right pointer left to decrease sum. Repeat until pointers cross. If no pair found, return false.

Practice

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

Solution

  1. Step 1: Understand the problem statement

    The problem asks to find if there exist two nodes in a Binary Search Tree (BST) such that their values add up to a given target sum.
  2. Step 2: Identify the goal

    The goal is to check for the existence of such a pair, not to find maximum, count nodes, or check balance.
  3. Final Answer:

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

    Two Sum in BST means finding two nodes summing to target [OK]
Hint: Look for two nodes adding to target in BST [OK]
Common Mistakes:
  • Confusing with finding max/min value
  • Thinking it counts nodes instead of pairs
  • Assuming it checks tree balance
2. Which of the following C++ code snippets correctly declares a BST node structure for the Two Sum problem?
easy
A. struct TreeNode { int val; TreeNode left; TreeNode* right; };
B. struct TreeNode { int val; TreeNode left; TreeNode right; };
C. struct TreeNode { int val; TreeNode* left; TreeNode* right; };
D. struct TreeNode { int val; TreeNode* left; TreeNode right; };

Solution

  1. Step 1: Check pointer usage in struct

    In C++, child nodes in a tree are pointers to TreeNode objects, so left and right must be pointers.
  2. Step 2: Validate each option

    struct TreeNode { int val; TreeNode* left; TreeNode* right; }; uses TreeNode* for left and right, which is correct. Options A, B, and C incorrectly use TreeNode without pointers for one or both children.
  3. Final Answer:

    struct TreeNode { int val; TreeNode* left; TreeNode* right; }; -> Option C
  4. Quick Check:

    BST nodes use pointers for children [OK]
Hint: Children in BST nodes are pointers in C++ [OK]
Common Mistakes:
  • Using objects instead of pointers for children
  • Mixing pointer and non-pointer types
  • Forgetting semicolon after struct
3. What is the output of the following code snippet that checks for two sum in BST?
struct TreeNode {
  int val;
  TreeNode* left;
  TreeNode* right;
  TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

bool findTarget(TreeNode* root, int k) {
  std::unordered_set<int> seen;
  std::function dfs = [&](TreeNode* node) {
    if (!node) return false;
    if (seen.count(k - node->val)) return true;
    seen.insert(node->val);
    return dfs(node->left) || dfs(node->right);
  };
  return dfs(root);
}

int main() {
  TreeNode* root = new TreeNode(5);
  root->left = new TreeNode(3);
  root->right = new TreeNode(6);
  root->left->left = new TreeNode(2);
  root->left->right = new TreeNode(4);
  root->right->right = new TreeNode(7);
  
  bool result = findTarget(root, 9);
  std::cout << (result ? "true" : "false") << std::endl;
  return 0;
}
medium
A. true
B. false
C. Compilation error
D. Runtime error

Solution

  1. Step 1: Understand the tree and target

    The BST has nodes 5,3,6,2,4,7. The target sum is 9.
  2. Step 2: Trace the DFS and set usage

    DFS visits nodes and checks if (target - current node value) is in the set. For example, when visiting node 6, it checks if 9-6=3 is in set. Node 3 was visited before, so it returns true.
  3. Final Answer:

    true -> Option A
  4. Quick Check:

    3 + 6 = 9 found in BST [OK]
Hint: Check if complement exists in visited nodes set [OK]
Common Mistakes:
  • Assuming no pair exists without checking all nodes
  • Confusing DFS order with BFS
  • Ignoring the use of hash set for complements
4. Identify the bug in the following Two Sum in BST code snippet and select the correct fix:
bool findTarget(TreeNode* root, int k) {
  std::unordered_set<int> seen;
  std::function dfs = [&](TreeNode* node) {
    if (!node) return false;
    if (seen.count(k - node->val)) return true;
    dfs(node->left);
    dfs(node->right);
    seen.insert(node->val);
    return false;
  };
  return dfs(root);
}
medium
A. Insert node->val before recursive calls to children
B. Remove the unordered_set and use a vector instead
C. Change return false to return true at the end
D. Add a null check after inserting node->val

Solution

  1. Step 1: Analyze the order of operations

    The code inserts node->val into the set after recursive calls, so complements are not found when visiting children.
  2. Step 2: Fix the insertion timing

    Insert node->val before recursive calls so that children can find complements in the set.
  3. Final Answer:

    Insert node->val before recursive calls to children -> Option A
  4. Quick Check:

    Insert before recursion to find complements [OK]
Hint: Insert current value before recursion to detect complements [OK]
Common Mistakes:
  • Inserting after recursion causes missed pairs
  • Changing return values incorrectly
  • Replacing set with vector reduces efficiency
5. Given a BST with nodes [10, 5, 15, 3, 7, null, 18], how would you modify the Two Sum in BST algorithm to handle the case where the target sum is twice the value of a single node (e.g., target = 14 and node value = 7)?
hard
A. Only check leaf nodes for pairs
B. Ignore pairs where complement equals current node value
C. Use a sorted array instead of a hash set
D. Check if the complement equals the current node value and ensure the node appears twice

Solution

  1. Step 1: Understand the problem with duplicates

    If target is twice a node's value, we must ensure two distinct nodes with that value exist.
  2. Step 2: Modify algorithm to handle duplicates

    When complement equals current node value, check if the node appears twice (e.g., by counting occurrences or checking different nodes).
  3. Final Answer:

    Check if the complement equals the current node value and ensure the node appears twice -> Option D
  4. Quick Check:

    Handle duplicates by verifying two distinct nodes [OK]
Hint: Verify two distinct nodes if complement equals current value [OK]
Common Mistakes:
  • Ignoring duplicate values causing false positives
  • Skipping pairs with same node value
  • Switching data structures unnecessarily
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