Skip to content

Two Sum IV - Input is a BST Solution Added in java language. #106

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Solution {
public int search(int[] nums, int target) {

int start = 0;
int end = nums.length-1;

while(start<=end){

int mid = start+end>>>1;

if(nums[mid]==target){
return mid;
}else if(nums[mid]<target){
start = mid+1;
}else end = mid-1;

}

return -1;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */

public class Solution extends VersionControl {
public int firstBadVersion(int n) {

int start = 1;
int end = n;

while(start<end){
int mid = start+end>>>1;

if(isBadVersion(mid)){
end = mid;
}else start = mid+1;

}

return start;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution {
public int searchInsert(int[] nums, int target) {

int start = 0;
int end = nums.length-1;

while(start<=end){

int mid = start+end>>>1;

if(nums[mid]==target) return mid;
else if(target<nums[mid]){
end = mid-1;
}else{
start = mid+1;
}

}


return start;
}
}
41 changes: 41 additions & 0 deletions Two Sum IV - Input is a BST.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean findTarget(TreeNode root, int k) {

if(root.left==null && root.right==null) return false;

Set<Integer> set = new HashSet<>();
getVals(root,set);

for(int i:set){
if(set.contains(k-i) && i!=k-i) return true;
}

return false;
}

void getVals(TreeNode root, Set<Integer> set){

if(root==null) return;

set.add(root.val);
getVals(root.left,set);
getVals(root.right,set);

}

}