653. Two Sum IV - Input is a BST
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: TrueInput:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: FalseLast updated
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
Output: TrueInput:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output: FalseLast updated
class Solution {
public boolean findTarget(TreeNode root, int k) {
HashSet<Integer> set = new HashSet<>();
return find(root, k, set);
}
public boolean find(TreeNode root, int k, HashSet<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);
}
}class Solution {
public boolean findTarget(TreeNode root, int k) {
Set<Integer> seen = new HashSet<>();
Queue<TreeNode> searchQueue = new LinkedList<>();
if (root != null) searchQueue.add(root);
while (!searchQueue.isEmpty()) {
TreeNode current = searchQueue.remove();
if (seen.contains(k - current.val)) return true;
seen.add(current.val);
if (current.left != null) searchQueue.add(current.left);
if (current.right != null) searchQueue.add(current.right);
}
return false;
}
}class Solution {
public boolean findTarget(TreeNode root, int k) {
return dfs(root, root, k);
}
public boolean dfs(TreeNode root, TreeNode cur, int k) {
// iterate on the cur node
if(cur == null) return false;
return search(root, cur, k - cur.val)
|| dfs(root, cur.left, k)
|| dfs(root, cur.right, k);
}
public boolean search(TreeNode root, TreeNode cur, int k){
// search on the root node.
if(root == null) return false;
return (root.val == k) && (cur != root) //不能是同一个node加两遍
|| (root.val < k) && search(root.right, cur, k) //root的val已经比target小了,直接去右边找
|| (root.val > k) && search(root.left, cur, k); //直接去左边找
}
}