给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,
则返回 true。案例 1:
输入:
5
/ \
3 6
/ \ \
2 4 7 Target = 9 输出: True
案例 2:
输入:
5
/ \
3 6
/ \ \
2 4 7 Target = 28 输出: False
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst
Hashset
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);
}
}
因为两个点可能在左右子树上 不能分两个部分分析
装入ArrayList之后 双指针遍历
class Solution {
public boolean findTarget(TreeNode root, int k) {
List<Integer> list = new ArrayList<>();
inorder(root,list);
int i=0,j=list.size()-1;
while(i<j){
int sum = list.get(i)+list.get(j);
if(sum == k) return true;
if(sum < k) i++;
else if(sum > k) j--;
}
return false;
}
public void inorder(TreeNode root,List<Integer> list){
if(root == null) return ;
inorder(root.left,list);
list.add(root.val);
inorder(root.right,list);
}
}