Search
while(low <= high){
int mid = low+((high-low)/2);
int value = nums[mid];
if(value == target){
return mid;
}else if(value > target){
low = mid+1;
}else{
high=mid-1;
}
}
Build Tree
import java.util.Scanner;
class TreeNode {
int value;
TreeNode left;
TreeNode right;
TreeNode(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
public class BSTTemplate {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = in.nextInt();
}
TreeNode root = buildTree(nums);
}
private static TreeNode buildTree(int[] nums) {
if (nums == null || nums.length == 0) {
return null;
}
TreeNode root = new TreeNode(nums[0]);
for (int i = 1; i < nums.length; i++) {
insertNode(root, nums[i]);
}
return root;
}
private static void insertNode(TreeNode root, int value) {
if (value < root.value) {
if (root.left == null) {
root.left = new TreeNode(value);
} else {
insertNode(root.left, value);
}
} else {
if (root.right == null) {
root.right = new TreeNode(value);
} else {
insertNode(root.right, value);
}
}
}
}
Think out of box, there is always a better way.
Comments | NOTHING