Two Sum IV - Input is a BST (LeetCode 653): Solution and Explanation

Easy
Hash Table
Two Pointers
Tree
Depth First Search
Binary Search Tree
Binary Tree

You get the root of a binary search tree and a target k. Return true if two different nodes have values that sum to k, and false otherwise.

Intuition

This is Two Sum with the numbers stored in a tree. The tree is a binary search tree, which means its values have an order you can read off for free: an inorder traversal visits them from smallest to largest.

Once the values are in a sorted list, the sorted version of Two Sum applies. Put one pointer on the smallest value and one on the largest. Their sum tells you which pointer is useless.

If the sum is too small, the smallest value cannot be part of any answer, because even the largest remaining partner was not enough. Drop it by moving the left pointer right. If the sum is too large, the largest value is useless for the mirror reason, so move the right pointer left. Each comparison removes one candidate, so the sweep is linear.

Approach: Inorder traversal plus two pointers

  1. Walk the tree inorder with an explicit stack: slide down the left edge pushing nodes, pop one, record its value, then move to its right child.
  2. The recorded list vals is sorted. Set lo = 0 and hi = len(vals) - 1.
  3. While lo < hi, compute s = vals[lo] + vals[hi].
  4. If s == k, return true. If s < k, move lo right. Otherwise move hi left.
  5. If the pointers meet, no pair exists; return false.

Step-by-step example

root = [5,3,6,2,4,null,7], k = 9
  1. The inorder walk visits 2, 3, 4, 5, 6, 7, so vals = [2, 3, 4, 5, 6, 7].
  2. lo points at 2 and hi points at 7. Their sum is 9, which equals k.
  3. Return true. The pair is the node 2 and the node 7.

Code: Python, Java, C++

1class Solution:
2    def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
3        vals = []
4        stack, node = [], root
5        while stack or node:
6            while node:
7                stack.append(node)
8                node = node.left
9            node = stack.pop()
10            vals.append(node.val)
11            node = node.right
12        lo, hi = 0, len(vals) - 1
13        while lo < hi:
14            s = vals[lo] + vals[hi]
15            if s == k:
16                return True
17            if s < k:
18                lo += 1
19            else:
20                hi -= 1
21        return False
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

The inorder walk touches each node once, and each step of the sweep moves one pointer, so it runs at most n - 1 times.

Space

O(n)

The sorted list holds all n values. The traversal stack adds O(h) on top.

Other approaches

Hash set during any traversal (time O(n), space O(n))

Visit nodes in any order and keep a set of values seen. For each node, check whether k minus its value is already in the set. This ignores the BST property and works on any binary tree.

Two BST iterators (time O(n), space O(h))

Run a forward inorder iterator and a reverse inorder iterator at the same time and move them like the two pointers. It avoids storing the list and uses only O(h) space, at the cost of more code.

Search the tree for each complement (time O(n h), space O(h))

For every node, search the BST for k minus its value, making sure the match is a different node. Simple but slower, and degrades to quadratic on a skewed tree.

Common mistakes

  • Pairing a node with itself. With k = 2 and a single node 1, the answer is false; the condition lo < hi (or checking the set before inserting) prevents this.
  • Using a recursive inorder walk in Python on a skewed tree with 10,000 nodes, which can exceed the recursion limit.
  • Moving the wrong pointer. A sum that is too small means the left value is too small, so the left pointer moves right.
  • Forgetting that values can be negative. The two-pointer logic does not care, but early exits like stopping when a value exceeds k are wrong.

Frequently asked questions

Why is the inorder list sorted?

In a BST, everything in a node's left subtree is smaller and everything in its right subtree is larger. Inorder visits left subtree, node, right subtree, so values come out in increasing order.

Is the hash set approach better?

It is also O(n) time and O(n) space, and it does not need the BST property. The two-pointer version shows how the BST order can replace hashing, and the iterator variant cuts the space to O(h).

Can two nodes have the same value?

Inputs are valid BSTs, which in this problem do not contain duplicates. The pointer version would still handle duplicates correctly because lo and hi always point at different nodes.

Why is moving one pointer per step safe?

When the sum is too small, the left value fails even with the largest remaining partner, so it fails with every partner and can be dropped. The same argument drops the right value when the sum is too large.