Browse curriculum

Two Sum IV - Input is a BST

Decide whether two different nodes of a binary search tree sum to k, with a DFS that checks each node's partner against a set of values already visited.

Problem Understanding

Two Sum IV - Input is a BST: given the root of a binary search tree and an integer k, return true if there are two different nodes whose values add up to k.

Examples: [5,3,6,2,4,null,7], k 9 → true (4 + 5); k 28 → false.

The Intuition: Two Sum With a Different Loop

Two Sum walks an array with a hash map of what it has seen. Walk the tree instead:

  1. Visit each node with a DFS.
  2. Look up its partner k − val in the set of values visited so far.
  3. Remember the value only after checking, so a node never pairs with itself.

Using the BST order instead, inorder gives sorted values (as in Binary Tree Inorder Traversal) and Two Sum II finishes the job with two pointers.

Interactive Walkthrough

k = 9 · OUTLINED = IN THE SET

EMPTY SET

need

:

answer

:

seen

Empty

 

Find two different nodes that add up to 9. Keep a set of the values visited so far

Next

Visit 5: its partner would be 9 − 5 = 4

root

k

Legend & Complexity

The node being visited

Nodes whose values are in the set

The pair that adds up to k

Time

O(n)

Space

O(n)

The node being visited is filled, nodes already in the set are outlined, and the set is listed beside the tree. Try Self pair to see why the check comes before the add.

Dry Run Table

Input: [5,3,6,2,4,null,7], k = 9 (preorder: 5, 3, 2, 4, …).

Node Need In set? Set after
5 4 no {5}
3 6 no {5, 3}
2 7 no {5, 3, 2}
4 5 yes

Answer: true (5 + 4 = 9).

The Solution Template

DFS with a set. The C version uses a flag array, since LeetCode bounds the values.

Two Sum IV - Input is a BST Code
1var findTarget = function(root, k) {
2 const seen = new Set();
3 const dfs = (node) => {
4 if (!node) return false;
5 if (seen.has(k - node.val)) return true;
6 seen.add(node.val);
7 return dfs(node.left) || dfs(node.right);
8 };
9 return dfs(root);
10};

Edge Cases & Common Mistakes

  • Single node: no pair possible; return false.
  • Adding before checking: lets a node pair with itself when k = 2 × val.
  • Searching only one subtree: the partner can be anywhere, including an ancestor.
  • Negative values: the set handles them; the C flag array offsets indices.
  • Early exit: return as soon as a pair is found.

Summary

Traverse the tree; at each node check whether k − val is already in a set, then add val. O(n) time and space; inorder + two pointers is the BST-specific alternative.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Visit

    Traverse the tree (preorder DFS is fine).

  2. Check

    At each node, if k - val is in the set, return true.

  3. Remember

    Otherwise add val to the set and continue; return false when the traversal ends.

Frequently asked questions

How is this Two Sum?

It is the same question on a different container. In Two Sum you scan an array and check whether target - x was seen; here you visit the tree's nodes in any order and check whether k - val was seen. The traversal just replaces the loop.


Why check the set before adding the node's value?

So a node cannot pair with itself. For k = 4 and a node holding 2, adding 2 first would make the check find 2 and wrongly return true. Checking first means only earlier nodes can be partners.


How does the BST property help?

An inorder traversal of a BST lists the values sorted, so you can run the two-pointer Two Sum II on that list: move the left pointer up if the sum is too small and the right pointer down if it is too big. That is O(n) time too, and with iterators on both ends it needs only O(h) extra space.


What is the complexity?

Each node is visited once with O(1) set operations, so O(n) time, and the set holds up to n values, so O(n) space. The search can stop early as soon as a pair is found.

New to the technique behind this problem? Watch it run step by step:

Depth First Search Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description