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.
Solution1 :
class Solution {
public boolean findTarget(TreeNode root, int k) {
HashSet<Integer> s = new HashSet<>(); //使用HashTable,检验是否存在k-root.val
return dfs(root, s, k);
}
private boolean dfs(TreeNode root, HashSet<Integer> s, int k) {
if (root == null)
return false;
if (s.contains(k - root.val))
return true;
s.add(root.val);
return dfs(root.left, s, k) || dfs(root.right, s, k);
}
}
Solution2://使用ArrayList存一个有序的数组,二叉树里的值从小到大排列(inorder方法的作用)
class Solution {
public boolean findTarget(TreeNode root, int k) {
List<Integer> l = new ArrayList<>();
inorder(root, l);
for (int i = 0, j = l.size() - 1; i < j;) {
if (l.get(i) + l.get(j) == k)
return true;
else if (l.get(i) + l.get(j) < k)
i++;
else j--;
}
return false;
}
private void inorder(TreeNode root, List<Integer> l) {
if (root == null)
return ;
inorder(root.left, l);
l.add(root.val);
inorder(root.right, l);
}
}