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.
X.
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/106110/Java-Code-O(n)-time-O(lg(n))-space-using-DFS-%2B-Stack
https://discuss.leetcode.com/topic/98440/java-c-three-simple-methods-choose-one-you-like
X. https://leetcode.com/articles/two-sum-iv/
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.
Example 1:
Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 9 Output: True
Example 2:
Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 28 Output: False
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/106110/Java-Code-O(n)-time-O(lg(n))-space-using-DFS-%2B-Stack
The idea of using interator is from 173. Binary Search Tree Iterator. Since the in-order treversal of BST ouputs the value in ascending order, we can use iterator to get next smallest value in O(1) average time. Similarly, we can also implement a reverse iterator to get next largest value each time from BST. (For how to use stack to implement iterator, please refer to: https://discuss.leetcode.com/topic/6604/ideal-solution-using-stack-java)
With those two iterators in hand, now we can use two pointers to solve the problem.
Since the size iterator(stack) is the height of the BST tree, it only requries O(lg(n)) space.
So the overall performace is: O(n)/O(lg(n)).
public boolean findTarget(TreeNode root, int k) {
Stack<TreeNode> stackL = new Stack<TreeNode>(); // iterator 1 that gets next smallest value
Stack<TreeNode> stackR = new Stack<TreeNode>(); // iterator 2 that gets next largest value
for(TreeNode cur = root; cur != null; cur = cur.left)
stackL.push(cur);
for(TreeNode cur = root; cur != null; cur = cur.right)
stackR.push(cur);
while(stackL.size() != 0 && stackR.size() != 0 && stackL.peek() != stackR.peek()){
int tmpSum = stackL.peek().val + stackR.peek().val;
if(tmpSum == k) return true;
else if(tmpSum < k)
for(TreeNode cur = stackL.pop().right; cur != null; cur = cur.left)
stackL.push(cur);
else
for(TreeNode cur = stackR.pop().left; cur != null; cur = cur.right)
stackR.push(cur);
}
return false;
}
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/106061/Java-Simple-AC-with-Time-O(n)-Space-O(log-n)-in-AverageUse the stack and search just like 2sum without dumping all the value out in the beginning.
-- Time/Space: n/logn in average
public boolean findTarget(TreeNode root, int k) {
if(root == null) return false;
Stack<TreeNode> l_stack = new Stack<>();
Stack<TreeNode> r_stack = new Stack<>();
stackAdd(l_stack, root, true);
stackAdd(r_stack, root, false);
while(l_stack.peek() != r_stack.peek()){
int n = l_stack.peek().val + r_stack.peek().val;
if(n == k){
return true;
}else if(n > k){
stackNext(r_stack, false);
}else{
stackNext(l_stack, true);
}
}
return false;
}
private void stackAdd(Stack<TreeNode> stack, TreeNode node, boolean isLeft){
while(node != null){
stack.push(node);
node = (isLeft) ? node.left : node.right;
}
}
private void stackNext(Stack<TreeNode> stack, boolean isLeft){
TreeNode node = stack.pop();
if(isLeft){
stackAdd(stack, node.right, isLeft);
}else{
stackAdd(stack, node.left, isLeft);
}
}
https://discuss.leetcode.com/topic/98440/java-c-three-simple-methods-choose-one-you-like
This method also works for those who are not BSTs. The idea is to use a hashtable to save the values of the nodes in the BST. Each time when we insert the value of a new node into the hashtable, we check if the hashtable contains
k - node->val
.
Time Complexity:
O(n)
, Space Complexity: O(n)
. public boolean findTarget(TreeNode root, int k) {
HashSet<Integer> set = new HashSet<>();
return dfs(root, set, k);
}
public boolean dfs(TreeNode root, HashSet<Integer> set, int k){
if(root == null)return false;
if(set.contains(k - root.val))return true;
set.add(root.val);
return dfs(root.left, set, k) || dfs(root.right, set, k);
}
The idea is to use a sorted array to save the values of the nodes in the BST by using an inorder traversal. Then, we use two pointers which begins from the start and end of the array to find where there is a sum
k
.
Time Complexity:
O(n)
, Space Complexity: O(n)
. public boolean findTarget(TreeNode root, int k) {
List<Integer> nums = new ArrayList<>();
inorder(root, nums);
for(int i = 0, j = nums.size()-1; i<j;){
if(nums.get(i) + nums.get(j) == k)return true;
if(nums.get(i) + nums.get(j) < k)i++;
else j--;
}
return false;
}
public void inorder(TreeNode root, List<Integer> nums){
if(root == null)return;
inorder(root.left, nums);
nums.add(root.val);
inorder(root.right, nums);
}
The idea is to use binary search method. For each node, we check if
k - node->val
exists in this BST.
Time Complexity:
O(nlogn)
, Space Complexity: O(h)
. h
is the height of the tree, which is logn
at best case, and n
at worst case. public boolean findTarget(TreeNode root, int k) {
return dfs(root, root, k);
}
public boolean dfs(TreeNode root, TreeNode cur, int k){
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 value){
if(root == null)return false;
return (root.val == value) && (root != cur)
|| (root.val < value) && search(root.right, cur, value)
|| (root.val > value) && search(root.left, cur, value);
}
X. https://leetcode.com/articles/two-sum-iv/
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;
}