653 Two Sum IV - Input is a BST: 05/17
Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True
Example 2
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: False
- [x] ### use set to store the difference between the target value and the current value, then when you encounter the difference return true, else return false
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Set<Integer> set = new HashSet<>();
public boolean findTarget(TreeNode root, int k) {
if(root == null) {
return false;
}
if (set.contains(root.val)) {
return true;
}else{
set.add(k - root.val);
}
return findTarget(root.left, k) || findTarget(root.right, k);
}
}