LeetCode #653 Easy

Two Sum IV — Input is BST

Two Sum IV - Input is a BST is LeetCode 653 (Easy). You get the root of a binary search tree and an integer k.

  • Return true if two different nodes have values that add up to k, and false otherwise.
  • Only a yes or no is needed, not the nodes themselves.

The tree can hold 10⁴ nodes and may be a single long chain, which matters for how you walk it.

Constraints
  • The number of nodes in the tree is in the range [1, 10⁴].
  • -10⁴ <= Node.val <= 10⁴
  • root is guaranteed to be a valid binary search tree.
  • -10⁵ <= k <= 10⁵
bsthash-tabletwo-pointers
Open on LeetCode ↗
02

Intuition

Visit the nodes one by one and remember every value you have already seen. When you stand on a node with value v, the only partner that works is k - v.

  • Partner seen: some earlier node holds k - v, so the answer is true.
  • Not seen yet: record v. If its partner comes later, that later node will find v in the set.

Each pair is caught by whichever of its two nodes is visited second, so one pass is enough.

How to spot this pattern

"Do two items add up to k" over any collection is a seen-set lookup. When the collection is a BST, its in-order walk is already sorted, which also opens up two pointers.

03

Approach

Try it first

Before reading on, decide what you need to remember about nodes you have already passed, and in which order to check and record so that one node cannot pair with itself. Then think about a tree that is one long chain. Aim for O(n) time.

1

Walk the tree with your own stack

Start with stack = [root] and an empty set seen. The stack does the job of recursion: it holds the nodes still waiting to be visited.

2

Check for the partner first

Pop a node. If k - node.val is in seen, return true: an earlier node and this one sum to k.

3

Record the value and push the children

Add node.val to seen, then push the right child and the left child if they exist. Pushing right first makes the left subtree come out of the stack first, which matches the usual top-down, left-first order.

4

Report false when the stack empties

If every node has been popped without a match, no two values sum to k, so return false.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findTarget(self, root, k):
▶3 seen = set()
▶4 stack = [root]
▶5 while stack:
▶6 node = stack.pop()
▶7 if k - node.val in seen:
▶8 return True
▶9 seen.add(node.val)
▶10 if node.right:
▶11 stack.append(node.right)
▶12 if node.left:
▶13 stack.append(node.left)
▶14 return False
536247partner neededseen valuesemptyto visit5← nextstart with the root, nothing seen
k9
seenempty
The stack holds the nodes still to visit, and the last one in comes out next. The seen set is empty, so the first node cannot find a partner yet.
536247partner needed9−5=4knodepartnerseen values5to visit63← nextnode 5 needs 4 → not seen, record 5
node5
partner4
seen5
No visited node holds 4. Record 5 so a later node can pair with it, and push its children, right first so the left comes out next.
536247partner needed9−3=6knodepartnerseen values53to visit642← nextnode 3 needs 6 → not seen, record 3
node3
partner6
seen5, 3
No visited node holds 6. Record 3 so a later node can pair with it, and push its children, right first so the left comes out next.
536247partner needed9−2=7knodepartnerseen values532to visit64← nextnode 2 needs 7 → not seen, record 2
node2
partner7
seen5, 3, 2
No visited node holds 7. Record 2 so a later node can pair with it; it has no children.
536247partner needed9−4=5knodepartnerseen values532to visit6← nextnode 4 needs 5 → already seen, true
node4
partner5
resulttrue
5 + 4 = 9, and 5 sits in the seen set, so an earlier node holds it. Two different nodes sum to k: return true without visiting the rest.
05

In-order list and two pointers

The iterative in-order walk goes as far left as possible, takes that node, then turns to its right subtree, so vals comes out sorted. Two pointers then close in from both ends of vals.

▶1class Solution:
▶2 def findTarget(self, root, k):
▶3 vals, stack, node = [], [], root
▶4 while stack or node:
▶5 while node:
▶6 stack.append(node)
▶7 node = node.left
▶8 node = stack.pop()
▶9 vals.append(node.val)
▶10 node = node.right
▶11 
▶12 l, r = 0, len(vals) - 1
▶13 while l < r:
▶14 s = vals[l] + vals[r]
▶15 if s == k:
▶16 return True
▶17 if s < k:
▶18 l += 1
▶19 else:
▶20 r -= 1
▶21 return False
06

Common pitfalls

Recording the value before checking

✗ Wrong
seen.add(node.val)
if k - node.val in seen:
    return True
✓ Right
if k - node.val in seen:
    return True
seen.add(node.val)

A node whose value is exactly half of k then finds itself. For the tree [5, 3, 6] and k = 10, the root adds 5, looks for 5, and returns true, but no two different nodes sum to 10.

Recursing on a tree that is one long chain

✗ Wrong
def dfs(node):
    ...
    return dfs(node.left) or dfs(node.right)
✓ Right
stack = [root]
while stack:
    node = stack.pop()
    ...

A BST built from sorted values is a single chain, and 10⁴ nodes means 10⁴ nested calls. Python stops at 1,000 by default and raises RecursionError; an explicit stack has no such limit.

07

Edge cases

A tree with one node

There is no second node to pair with, so the set is empty when the root is checked and the answer is false, whatever k is.

08

Complexity

Time
O(n)
Space
O(n)
Each node is popped once, and each set lookup and insert is O(1) on average. The set can hold all n values, and the stack holds at most one pending child per level plus the nodes beside it.
09

Two Sum IV — Input is BST FAQ

Does this ignore the fact that the tree is a BST?

Yes. The set works on any binary tree. The BST property is what the in-order version uses: an in-order walk lists the values in sorted order, so two pointers can then find the pair without a hash set.

Can it be done in O(h) extra space?

Yes, with two BST iterators: one walks in-order from the smallest value, the other in reverse from the largest, each keeping only a stack of height h. Advance the small side when the sum is too low and the large side when it is too high, and stop when the two meet.