一、题目描述
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.
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: True
二、题解
方法一:set + x 序遍历
* 注:不能把 map.put(root.val),因为先放去,如果 sum - root.val 刚好等于这个数的补数,树只有一个结点的时候,你是找不到两个数的。
Set<Integer> set;
int sum;
boolean exist = false;
public boolean findTarget(TreeNode root, int k) {
set = new HashSet<>();
sum = k;
dfs(root);
return exist;
}
private void dfs(TreeNode root) {
if (root == null)
return;
if (set.contains(sum - root.val)) {
exist = true;
return;
}
set.add(root.val);
dfs(root.left);
dfs(root.right);
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,
方法二:中序遍历 + 双指针(没想道)
中序遍历一次 BST 会得到一个有序的序列,然后通过双指针找回比较快。没想道的原因是: * 没有读清楚题目(输入的 BST)
List<Integer> arr;
public boolean findTarget(TreeNode root, int k) {
arr = new ArrayList<>();
inOr(root);
int l = 0, r = arr.size()-1;
while (l < r) {
int sum = arr.get(l) + arr.get(r);
if (sum > k) r--;
else if (sum < k) l++;
else return true;
}
return false;
}
void inOr(TreeNode root) {
if (root == null) return;
inOr(root.left);
arr.add(root.val);
inOr(root.right);
}
复杂度分析
- 时间复杂度: ,
- 空间复杂度: ,