Two Sum IV - Input is a BST

Does the BST contain two distinct nodes summing to k? Inorder + two-pointer or hash-set traversal.

Easy
Time O(n) Space O(n)
LeetCode
3 min read
tree bst hash-set

Problem#

Given the root of a BST and an integer k, return whether any pair of distinct node values sums to k.

Examples#

  • root [5,3,6,2,4,null,7], k = 9true (2 + 7).
  • root [5,3,6,2,4,null,7], k = 28false.

Constraints#

  • 1 <= n <= 10^4, -10^4 <= Node.val <= 10^4, -10^5 <= k <= 10^5.

Hints#

Hint
Treat it like Two Sum: traverse once, for each value look up k - val in a set.

Approach#

Any traversal works; the BST property is a red herring for the hash-set solution. For each visited node, return true if k - node->val has been seen; otherwise insert node->val.

Solution#

Two Sum IV - Input is a BST
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
unordered_set<int> seen;
function<bool(TreeNode*)> dfs = [&](TreeNode* n) {
if (!n) return false;
if (seen.count(k - n->val)) return true;
seen.insert(n->val);
return dfs(n->left) || dfs(n->right);
};
return dfs(root);
}
};

Editorial#

The BST shape makes an alternative O(n) / O(h) approach available: inorder traversal yields sorted values, then a two-pointer scan checks pairs. The hash-set version is simpler and runs in the same big-O time with O(n) space.

Complexity#

  • Time: O(n).
  • Space: O(n) for the set (and recursion stack).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.