Bird
Raised Fist0
DSA Typescriptprogramming~10 mins

Two Sum in BST in DSA Typescript - Execution Trace

Choose your learning style10 modes available
Concept Flow - Two Sum in BST
Start at root node
↓
Initialize empty set for complements
↓
Inorder traversal: go left
↓
Visit node: check if complement exists in set
↓
Return true
↓
Traverse right
↓
Repeat until all nodes visited or pair found
↓
If no pair found, return false
Traverse BST inorder, check if complement of current node value exists in a set; if yes, return true, else add value and continue.
Execution Sample
DSA Typescript
function findTarget(root: TreeNode | null, k: number): boolean {
  const set = new Set<number>();
  function inorder(node: TreeNode | null): boolean {
    if (!node) return false;
    if (inorder(node.left)) return true;
    if (set.has(k - node.val)) return true;
    set.add(node.val);
    return inorder(node.right);
  }
  return inorder(root);
}
This code checks if there exist two nodes in BST whose values sum to k by inorder traversal and using a set to track complements.
Execution Table
StepOperationCurrent Node ValueSet ContentsActionVisual State
1Start at root5{}Traverse left subtree5 / \ 3 6 / \ 2 4 7
2Traverse left3{}Traverse left subtree5 / \ 3 6 / \ 2 4 7
3Traverse left2{}Traverse left subtree5 / \ 3 6 / \ 2 4 7
4Visit node2{}Check complement 9 - 2 = 7 in set? No5 / \ 3 6 / \ 2 4 7
5Add to set2{2}Add 2 to set5 / \ 3 6 / \ 2 4 7
6Traverse rightnull{2}No right child, backtrack5 / \ 3 6 / \ 2 4 7
7Visit node3{2}Check complement 9 - 3 = 6 in set? No5 / \ 3 6 / \ 2 4 7
8Add to set3{2,3}Add 3 to set5 / \ 3 6 / \ 2 4 7
9Traverse right4{2,3}Traverse right subtree5 / \ 3 6 / \ 2 4 7
10Visit node4{2,3}Check complement 9 - 4 = 5 in set? No5 / \ 3 6 / \ 2 4 7
11Add to set4{2,3,4}Add 4 to set5 / \ 3 6 / \ 2 4 7
12Traverse rightnull{2,3,4}No right child, backtrack5 / \ 3 6 / \ 2 4 7
13Visit node5{2,3,4}Check complement 9 - 5 = 4 in set? Yes5 / \ 3 6 / \ 2 4 7
14Return5{2,3,4}Pair found (5 + 4 = 9), return true5 / \ 3 6 / \ 2 4 7
💡 At step 13, complement 4 found in set, so pair summing to 9 exists, traversal stops.
Variable Tracker
VariableStartAfter Step 5After Step 8After Step 11After Step 13Final
set{}{2}{2,3}{2,3,4}{2,3,4}{2,3,4}
current node523455
found pairfalsefalsefalsefalsetruetrue
Key Moments - 3 Insights
Why do we check if (k - node.val) is in the set before adding node.val?
Because we want to find if a previously visited node's value complements the current node to sum to k. Checking first (step 13) ensures we detect the pair immediately without missing it.
Why do we use inorder traversal instead of any other traversal?
Inorder traversal visits nodes in ascending order for BST, but here it's mainly to visit all nodes systematically. The set handles complement checks, so traversal order doesn't affect correctness.
What happens if the BST is empty?
The traversal immediately returns false at step 1 because the root is null, so no nodes to check, no pairs possible.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the set contents after step 8?
A{2,3}
B{2}
C{2,3,4}
D{}
💡 Hint
Check the 'Set Contents' column at step 8 in the execution_table.
At which step does the traversal find the pair that sums to k?
AStep 11
BStep 13
CStep 5
DStep 9
💡 Hint
Look for the step where 'Check complement' finds a value in the set.
If the target sum k was 10 instead of 9, what would happen at step 13?
AComplement 5 would be found in set, return true
BComplement 6 would be found, return true
CComplement 5 would not be found, continue traversal
DTraversal would stop immediately
💡 Hint
At step 13, node value is 5; check if (k - 5) is in set. For k=10, complement is 5.
Concept Snapshot
Two Sum in BST:
- Traverse BST inorder
- Use a set to store visited node values
- For each node, check if (target - node.val) in set
- If yes, return true immediately
- Else add node.val to set and continue
- Return false if no pair found
Full Transcript
This visualization shows how to find two numbers in a binary search tree that add up to a target sum k. We do an inorder traversal of the BST, visiting nodes from smallest to largest. At each node, we check if the complement (k minus current node's value) is already in a set of visited values. If it is, we found a pair and return true. If not, we add the current node's value to the set and continue. The execution table tracks each step, showing the current node, the set contents, and actions taken. The variable tracker shows how the set and current node change over time. Key moments clarify why we check complements before adding values and what happens if the tree is empty. The quiz tests understanding of set contents and when the pair is found. The snapshot summarizes the approach in simple steps.

Practice

(1/5)
1. What is the main goal of the Two Sum in BST problem?
easy
A. Check if a BST is balanced
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. Find the maximum value in a BST

Solution

  1. 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.
  2. Step 2: Identify the goal

    The goal is to check if such a pair exists, 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 = Find pair with target sum [OK]
Hint: Look for two values adding to target in BST [OK]
Common Mistakes:
  • Confusing with finding max or min value
  • Thinking it counts nodes instead of finding pairs
  • Assuming it checks tree balance
2. Which TypeScript syntax correctly defines a BST node for the Two Sum problem?
easy
A. interface TreeNode { val: string; left: TreeNode; right: TreeNode; }
B. function TreeNode(val) { this.val = val; this.left = null; this.right = null; }
C. type TreeNode = { val: number; left?: TreeNode; right?: TreeNode; }
D. class TreeNode { val: number; left: TreeNode | null; right: TreeNode | null; constructor(val: number) { this.val = val; this.left = null; this.right = null; } }

Solution

  1. Step 1: Check correct TypeScript class syntax for BST node

    class TreeNode { val: number; left: TreeNode | null; right: TreeNode | null; constructor(val: number) { this.val = val; this.left = null; this.right = null; } } defines a class with number value and nullable left/right children, matching BST node structure.
  2. Step 2: Compare other options

    function TreeNode(val) { this.val = val; this.left = null; this.right = null; } is JavaScript function style, not TypeScript class. interface TreeNode { val: string; left: TreeNode; right: TreeNode; } uses string type for val and non-nullable children, which is incorrect. type TreeNode = { val: number; left?: TreeNode; right?: TreeNode; } uses optional properties but lacks constructor and proper null handling.
  3. Final Answer:

    class TreeNode { val: number; left: TreeNode | null; right: TreeNode | null; constructor(val: number) { this.val = val; this.left = null; this.right = null; } } -> Option D
  4. Quick Check:

    Correct BST node class syntax = class TreeNode { val: number; left: TreeNode | null; right: TreeNode | null; constructor(val: number) { this.val = val; this.left = null; this.right = null; } } [OK]
Hint: Use class with nullable left/right and number val [OK]
Common Mistakes:
  • Using string type for node value
  • Not initializing left and right to null
  • Using JavaScript function instead of TypeScript class
3. Given the BST below and target = 9, what will the Two Sum function return?
    5
   / \
  3   7
 /     \
2       8
Function uses in-order traversal and a set to find pairs.
medium
A. true
B. false
C. null
D. Error

Solution

  1. Step 1: Traverse BST in-order and check pairs

    In-order traversal gives sorted values: [2, 3, 5, 7, 8]. We check if target - current value exists in set.
  2. Step 2: Find pair summing to 9

    Check pairs: 2 + 7 = 9 (found), so function returns true.
  3. Final Answer:

    true -> Option A
  4. Quick Check:

    2 + 7 = 9 found in BST [OK]
Hint: In-order traversal gives sorted list to find pairs [OK]
Common Mistakes:
  • Assuming no pair without checking all nodes
  • Confusing traversal order
  • Ignoring set lookup for complements
4. Identify the bug in this TypeScript Two Sum in BST function snippet:
function findTarget(root: TreeNode | null, k: number): boolean {
  const set = new Set<number>();
  function dfs(node: TreeNode | null): boolean {
    if (!node) return false;
    if (set.has(k - node.val)) return true;
    set.add(node.val);
    dfs(node.left);
    dfs(node.right);
    return false;
  }
  return dfs(root);
}
medium
A. The base case should return true when node is null
B. Set is not initialized properly
C. The function returns false too early, missing true from recursive calls
D. The function should use a queue instead of recursion

Solution

  1. Step 1: Analyze recursive calls and return values

    The dfs function calls dfs(node.left) and dfs(node.right) but ignores their return values, always returning false at the end.
  2. Step 2: Identify missing return propagation

    If dfs(node.left) or dfs(node.right) returns true, dfs should return true immediately to propagate the success.
  3. Final Answer:

    The function returns false too early, missing true from recursive calls -> Option C
  4. Quick Check:

    Return recursive true results to avoid missing pairs [OK]
Hint: Return recursive calls' results to propagate true [OK]
Common Mistakes:
  • Ignoring return values of recursive calls
  • Returning false before checking all nodes
  • Misunderstanding base case return
5. You want to optimize Two Sum in BST for large trees. Which approach best reduces time complexity while using O(h) space, where h is tree height?
hard
A. Use two pointers with iterative in-order and reverse in-order traversals simultaneously
B. Convert BST to array and use nested loops to find pairs
C. Use breadth-first search with a hash set to find pairs
D. Perform recursive DFS and store all node values in a list before checking pairs

Solution

  1. Step 1: Understand space and time constraints

    We want to reduce time complexity and keep space to O(h), where h is tree height.
  2. Step 2: Evaluate approaches

    Use two pointers with iterative in-order and reverse in-order traversals simultaneously uses two pointers with iterative in-order (smallest to largest) and reverse in-order (largest to smallest) traversals, allowing pair search in O(n) time and O(h) space. Other options use extra space O(n) or nested loops with O(n^2) time.
  3. Final Answer:

    Use two pointers with iterative in-order and reverse in-order traversals simultaneously -> Option A
  4. Quick Check:

    Two pointer BST traversal = O(n) time, O(h) space [OK]
Hint: Use two pointers with in-order and reverse in-order iterators [OK]
Common Mistakes:
  • Using nested loops causing O(n^2) time
  • Storing all nodes in list increasing space to O(n)
  • Using BFS which uses more space than O(h)
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