Two Sum IV - Input is a BST
Pattern: Two sum in BST
Treat the BST's inorder like a sorted array and use two pointers: one iterator walks up from the smallest value, another walks down from the largest. Move the small end up if the sum is too small and the large end down if it is too large.
The problem
Return whether two different nodes of the BST have values adding up to k. The example gives true for 9 and false
for 28. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- How is this like Two Sum on a sorted array?
- How do you walk a BST from the largest value down?
- When do you stop?
Hints
Brute force, and why it fails
Put every value in a hash set and look for k - v: O(n) time and O(n) memory.
The key insight
Two BST iterators give the two-pointer method with only O(h) memory.
Dry run
| lo | 2 |
|---|---|
| hi | 7 |
BST [5, 3, 6, 2, 4, null, 7], k = 9. Ends: 2 and 7, sum 9.
Step 1 of 3
The plan
lo = smallest, hi = largest
while lo is not hi: s = lo + hi; if s == k: true; if s < k: advance lo else: retreat hi
Complexity
- Time
O(n)- Space
O(h)
Each node is visited at most once by each iterator.
Edge cases
- One node: false.
- A value equal to k / 2 used twice: not allowed.
- Negative values.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public boolean findTarget(TreeNode root, int k) {
Deque<TreeNode> lo = new ArrayDeque<>(), hi = new ArrayDeque<>(); // inorder from the left, and from the right
for (TreeNode n = root; n != null; n = n.left) lo.push(n);
for (TreeNode n = root; n != null; n = n.right) hi.push(n);
while (!lo.isEmpty() && !hi.isEmpty() && lo.peek() != hi.peek()) { // two pointers on the sorted order
int s = lo.peek().val + hi.peek().val;
if (s == k) return true;
if (s < k) { // need a bigger sum: advance the small end
TreeNode n = lo.pop();
for (n = n.right; n != null; n = n.left) lo.push(n);
} else { // need a smaller sum: step the big end back
TreeNode n = hi.pop();
for (n = n.left; n != null; n = n.right) hi.push(n);
}
}
return false;
}
}C++
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
stack<TreeNode*> lo, hi; // inorder from the left, and from the right
for (TreeNode* n = root; n != NULL; n = n->left) lo.push(n);
for (TreeNode* n = root; n != NULL; n = n->right) hi.push(n);
while (!lo.empty() && !hi.empty() && lo.top() != hi.top()) { // two pointers on the sorted order
long long s = static_cast<long long>(lo.top()->val) + hi.top()->val;
if (s == k) return true;
if (s < k) { // need a bigger sum: advance the small end
TreeNode* n = lo.top();
lo.pop();
for (n = n->right; n != NULL; n = n->left) lo.push(n);
} else { // need a smaller sum: step the big end back
TreeNode* n = hi.top();
hi.pop();
for (n = n->left; n != NULL; n = n->right) hi.push(n);
}
}
return false;
}
};Python
class Solution:
def findTarget(self, root, k: int) -> bool:
lo, hi = [], [] # inorder from the left, and from the right
n = root
while n:
lo.append(n)
n = n.left
n = root
while n:
hi.append(n)
n = n.right
while lo and hi and lo[-1] is not hi[-1]: # two pointers on the sorted order
s = lo[-1].val + hi[-1].val
if s == k:
return True
if s < k: # need a bigger sum: advance the small end
n = lo.pop().right
while n:
lo.append(n)
n = n.left
else: # need a smaller sum: step the big end back
n = hi.pop().left
while n:
hi.append(n)
n = n.right
return FalseCommon mistakes
- Pairing a node with itself.
- Collecting all values into an array.