Skip to content

Instantly share code, notes, and snippets.

@nealhu
Created July 11, 2014 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nealhu/5580fa4178d2e81528df to your computer and use it in GitHub Desktop.
Save nealhu/5580fa4178d2e81528df to your computer and use it in GitHub Desktop.
CC_4_3
// Cracking the Coding Interview
// 4.3 Given a sorted (increasing order) array with unique integer elements,
// write an algorithm to create a binary search tree with minimal height.
class Node {
public int val;
public Node left;
public Node right;
Node(int v) {
val = v;
left = null;
right = null;
}
}
class SearchTree {
public static Node constructBST(int[] arr) {
int len = arr.length;
return constructBSTHelper(arr, 0, len-1);
}
public static Node constructBSTHelper(int[] arr, int low, int high) {
if (high < low) {
return null;
} else {
int mid = low + (high - low)/2;
Node root = new Node(arr[mid]);
root.left = constructBSTHelper(arr, low, mid-1);
root.right = constructBSTHelper(arr, mid+1, high);
return root;
}
}
}
@jason51122
Copy link

  1. Good job!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment