Skip to content

Instantly share code, notes, and snippets.

@jason51122
Created July 11, 2014 05:05
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 jason51122/471a22c93c3f65a663c6 to your computer and use it in GitHub Desktop.
Save jason51122/471a22c93c3f65a663c6 to your computer and use it in GitHub Desktop.
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 TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public TreeNode sortedArrayToBST(int[] num) {
if (num == null || num.length == 0) {
return null;
}
return helper(num, 0, num.length - 1);
}
private TreeNode helper(int[] num, int start, int end) {
if (start > end) {
return null;
}
int mid = start + (end - start) / 2;
TreeNode root = new TreeNode(num[mid]);
root.left = helper(num, start, mid - 1);
root.right = helper(num, mid + 1, end);
return root;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment