Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Constraints:
The number of nodes in the tree is in the range [1, 104].
-104 <= Node.val <= 104
root is guaranteed to be a valid binary search tree.
-105 <= k <= 105
给出BST,问其中是否存在两个节点值的和=k
思路:
涉及二叉数的遍历,Two sum。
二叉树的遍历随便选一个,这里选前序遍历,Two sum就用一个HashSet保存已经遍历过的数字,如果后面set里面保存的有k-root.val,就说明存在。
public boolean findTarget(TreeNode root, int k) {
HashSet<Integer> set = new HashSet<>();
return preTraversal(root, set, k);
}
boolean preTraversal(TreeNode root, HashSet<Integer> set, int k) {
if(root == null) return false;
if(set.contains(k - root.val)) return true;
set.add(root.val);
if(preTraversal(root.left, set, k)) return true;
if(preTraversal(root.right, set, k)) return true;
return false;
}