Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Created February 22, 2015 19:28
Show Gist options
  • Save dmnugent80/2a9f0325d6b30a4863c8 to your computer and use it in GitHub Desktop.
Save dmnugent80/2a9f0325d6b30a4863c8 to your computer and use it in GitHub Desktop.
Create Balanced BST from sorted array
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
return helper(num, 0, num.length - 1);
}
public TreeNode helper(int[] arr, int left, int right){
if (left > right) return null;
int mid = (left + right) / 2;
TreeNode node = new TreeNode(arr[mid]);
node.left = helper(arr, left, mid-1);
node.right = helper(arr, mid+1, right);
return node;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment