方法一:
将BST的值存储到HashMap中,转化为 两数和为目标值的问题;LeetCode 1 两数之和
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private HashMap<Integer,Integer> map = new HashMap<>();
public void BSTtoHashMap(TreeNode root){
if(root == null) return;
BSTtoHashMap(root.left);
map.put(root.val,1);
BSTtoHashMap(root.right);
}
public boolean findTarget(TreeNode root, int k) {
BSTtoHashMap(root);
return find(root,k);
}
public boolean find(TreeNode root,int k){
if(root == null) return false;
int subElem = k-root.val;
//subElem!=root.val,考虑 测试用例 [1] 2,即map中匹配的不能是元素自己
if(map.containsKey(subElem)&&subElem!=root.val){
return true;
}
boolean left = findTarget(root.left,k);
boolean right = findTarget(root.right,k);
return (left||right);
}
}
因为BST每个元素的值唯一,
也可以存储到HashSet中
这里把构建HashSet和遍历合到一步,提高了效率
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);
}
}
方法二:
BFS+HashSet
public class Solution {
public boolean findTarget(TreeNode root, int k) {
Set < Integer > set = new HashSet();
Queue < TreeNode > queue = new LinkedList();
queue.add(root);
while (!queue.isEmpty()) {
if (queue.peek() != null) {
TreeNode node = queue.remove();
if (set.contains(k - node.val))
return true;
set.add(node.val);
queue.add(node.right);
queue.add(node.left);
} else
queue.remove();
}
return false;
}
}
方法三:
利用BST的中序遍历是有序的,将本问题转化成LeetCode 167.两数之和
两数之和II的思路
public class Solution {
public boolean findTarget(TreeNode root, int k) {
List < Integer > list = new ArrayList();
inorder(root, list);
int l = 0, r = list.size() - 1;
while (l < r) {
int sum = list.get(l) + list.get(r);
if (sum == k)
return true;
if (sum < k)
l++;
else
r--;
}
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);
}
}