原题链接: https://leetcode.com/problems/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.
解题思路
LeetCode给出了三种方法,分别是递归(DFS)、BFS和二叉树。
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/solution/
1. 递归
按照DFS的顺序,先找到一个a,然后判断HashSet中是否有等于k-a的b,如果有k-a的话,就到了,否则把a放入这个集合。这里用递归做,优点是代码简单,缺点是Runtime和Memory都比较大。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
Set<Integer> con= new HashSet();
public boolean findTarget(TreeNode root, int k) {
if(root == null) {
return false;
}
if(con.contains(k-root.val)) {
return true;
}
else {
con.add(root.val);
}
return findTarget(root.left,k) || findTarget(root.right,k);
}
}
2. BFS
就是按照BFS的方式,扫描一遍树。
public class Solution {
List<Integer> con = new ArrayList();
Queue < TreeNode > qu = new LinkedList();
public boolean findTarget(TreeNode root, int k) {
qu.add(root);
while(qu.isEmpty()!= true) {
TreeNode a = qu.remove();
if(con.contains(k-a.val)) {
return true;
}
else {
con.add(a.val);
}
if(a.left != null) {
qu.add(a.left);
}
if(a.right!=null) {
qu.add(a.right);
}
}
return false;
}
}
queue的一些操作
add 增加一个元索 ,如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove 移除并返回队列头部的元素, 如果队列为空,则抛出一个NoSuchElementException异常
element 返回队列头部的元素, 如果队列为空,则抛出一个NoSuchElementException异常
offer 添加一个元素并返回true 如果队列已满,则返回false
poll 移除并返问队列头部的元素 如果队列为空,则返回null
peek 返回队列头部的元素 如果队列为空,则返回null
put 添加一个元素 如果队列满,则阻塞
take 移除并返回队列头部的元素 如果队列为空,则阻塞
3. 二叉树
二叉树有三种遍历方式:前序、中序、后序遍历。采用中序遍历,会将二叉树变为一个递增的数组。然后再使用二分,在这个递增的数组上用双指针l和r从两头逼近就可以了。
class Solution {
List<Integer> con = new ArrayList();
public boolean findTarget(TreeNode root, int k) {
inorder(root,con);
int l = 0;
int r = con.size()-1;
while(l < r) {
int sum = con.get(l) + con.get(r);
if(sum == k) {return true;}
else if(sum > k) {r--;}
else {l++;}
}
return false;
}
public void inorder(TreeNode root,List<Integer> con) {
if(root == null) {
return;
}
inorder(root.left,con);
con.add(root.val);
inorder(root.right,con);
}
}
参考资料
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/solution/
https://www.cnblogs.com/lemon-flm/p/7877898.html
n-Sum专题相关题目
1. Two Sum
15. 3Sum
16. 3Sum Closest
18. 4Sum
167. Two Sum II - Input array is sorted
560. Subarray Sum Equals K
653. Two Sum IV - Input is a BST