Created
July 11, 2014 00:33
-
-
Save nealhu/5580fa4178d2e81528df to your computer and use it in GitHub Desktop.
CC_4_3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
commented
Jul 11, 2014
- Good job!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment