0
0
DSA C++programming~10 mins

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

Choose your learning style9 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.