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
trueif two different nodes have values that add up tok, andfalseotherwise. - 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.
- 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⁵
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 istrue. - Not seen yet: record
v. If its partner comes later, that later node will findvin the set.
Each pair is caught by whichever of its two nodes is visited second, so one pass is enough.
"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.
Approach
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.
Two ways to solve it
Walk the nodes once, checking each value's partner against the values already passed.
- Early exit: stops at the first match.
- Any tree: does not rely on BST order.
The shortest correct answer.
Collect the values in-order, which gives a sorted list, then move pointers in from both ends.
- Uses the BST: sorted order comes for free.
- Cost: always visits every node first.
The step towards the O(h) two-iterator follow-up.
Both are O(n) time and O(n) space. The seen set wins because it is one pass with an early exit and works on any tree. The steps, code and live demo follow the seen set; the in-order version comes after the demo.
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.
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.
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.
Report false when the stack empties
If every node has been popped without a match, no two values sum to k, so return false.
Code in Python, C++ and Java
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.
Common pitfalls
Recording the value before checking
seen.add(node.val)
if k - node.val in seen:
return Trueif 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
def dfs(node):
...
return dfs(node.left) or dfs(node.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.
Edge cases
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.
Complexity
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.