653. two sum iv – input is a bst 解答

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.

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Solution {
public boolean findTarget(TreeNode root, int k) {
Set < Integer > set = new HashSet();
return find(root, k, set);
}
public boolean find(TreeNode root, int k, Set < Integer > set) {
if (root == null)
return false;
if (set.contains(k - root.val))
return true;
set.add(root.val);
return find(root.left, k, set) || find(root.right, k, set);
}
}