@@ -0,0 +1,2318 @@
+package com.freetymekiyan.algorithms.level.medium;%0A%0Aimport java.util.ArrayList;%0Aimport java.util.HashSet;%0Aimport java.util.List;%0Aimport java.util.Set;%0A%0Aimport static com.freetymekiyan.algorithms.utils.Utils.TreeNode;%0A%0A/**%0A * 653. Two Sum IV - Input is a BST%0A * %3Cp%3E%0A * Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their%0A * sum is equal to the given target.%0A * %3Cp%3E%0A * Example 1:%0A * Input:%0A * %7C     5%0A * %7C    / %5C%0A * %7C   3   6%0A * %7C  / %5C   %5C%0A * %7C 2   4   7%0A * %3Cp%3E%0A * Target = 9%0A * %3Cp%3E%0A * Output: True%0A * Example 2:%0A * Input:%0A * %7C     5%0A * %7C    / %5C%0A * %7C   3   6%0A * %7C  / %5C   %5C%0A * %7C 2   4   7%0A * %3Cp%3E%0A * Target = 28%0A * %3Cp%3E%0A * Output: False%0A * %3Cp%3E%0A * Related Topics: Tree%0A * Similar Questions: (E) Two Sum, (E) Two Sum II - Input array is sorted, (E) Two Sum III - Data structure design%0A */%0Apublic class TwoSumIVBST %7B%0A%0A    /**%0A     * Set.%0A     * Traverse the tree and add traversed node values to a set.%0A     * At every new node, check if target - current node's value exists in the set.%0A     */%0A    public boolean findTarget(TreeNode root, int k) %7B%0A        Set%3CInteger%3E visited = new HashSet%3C%3E();%0A        return find(root, k, visited);%0A    %7D%0A%0A    private boolean find(TreeNode root, int t, Set%3CInteger%3E visited) %7B%0A        if (root == null) return false;%0A        if (visited.contains(t - root.val)) return true;%0A        visited.add(root.val);%0A        return find(root.left, t, visited) %7C%7C find(root.right, t, visited);%0A    %7D%0A%0A    /**%0A     * BST, In-Order Traversal, Two Pointers.%0A     * In-order traversal generates values in ascending order.%0A     * Then use two pointers to check the target.%0A     */%0A    public boolean findTarget2(TreeNode root, int k) %7B%0A        List%3CInteger%3E values = new ArrayList%3C%3E();%0A        inOrderTraverse(root, values);%0A        int start = 0, end = values.size() - 1;%0A        while (start %3C end) %7B%0A            int sum = values.get(start) + values.get(end);%0A            if (sum == k) return true;%0A            if (sum %3E k) end--;%0A            else if (sum %3C k) start++;%0A        %7D%0A        return false;%0A    %7D%0A%0A    private void inOrderTraverse(TreeNode root, List%3CInteger%3E values) %7B%0A        if (root == null) return;%0A        inOrderTraverse(root.left, values);%0A        values.add(root.val);%0A        inOrderTraverse(root.right, values);%0A    %7D%0A%7D%0A

add 653. Two Sum IV - Input is a BST