Visit nodes; if k − value is in the set, return true; otherwise add the value.
Approach 1
import java.util.HashSet;
import java.util.Set;
class Solution {
public boolean findTarget(TreeNode root, int k) {
return dfs(root, k, new HashSet<>());
}
private boolean dfs(TreeNode n, int k, Set<Integer> seen) {
if (n == null) return false;
if (seen.contains(k - n.val)) return true;
seen.add(n.val);
return dfs(n.left, k, seen) || dfs(n.right, k, seen);
}
}
Verdict: Works for any binary tree.
2
In-order list + two pointers
Time O(n) Space O(n)
Collect values in sorted order, then move pointers inward from both ends.
Approach 2
import java.util.ArrayList;
import java.util.List;
class Solution {
public boolean findTarget(TreeNode root, int k) {
List<Integer> a = new ArrayList<>();
inorder(root, a);
int l = 0, r = a.size() - 1;
while (l < r) {
int s = a.get(l) + a.get(r);
if (s == k) return true;
if (s < k) l++; else r--;
}
return false;
}
private void inorder(TreeNode n, List<Integer> a) {
if (n == null) return;
inorder(n.left, a); a.add(n.val); inorder(n.right, a);
}
}
Verdict: Uses the BST ordering.
Before you submit
Edge cases and common mistakes
Test these inputs
Single node
k = 2 × a value (the same node can't be used twice)
Mistakes people make
Adding the value to the set before checking (matches a node with itself).