Skip to content

Instantly share code, notes, and snippets.

@sogwiz
Created July 22, 2019 18:34
Show Gist options
  • Save sogwiz/aeb03fad68aff515989fb2121cafc29e to your computer and use it in GitHub Desktop.
Save sogwiz/aeb03fad68aff515989fb2121cafc29e to your computer and use it in GitHub Desktop.
//RECURSIVE
public TreeNode sortedArrayToBSTRecursive(int[] nums) {
if(nums == null)return null;
TreeNode root = sortedArrayToBSTHelper(nums,0,nums.length-1);
return root;
}
public TreeNode sortedArrayToBSTHelper(int[] nums, int begin, int end) {
if(nums == null)return null;
if(begin > end) return null;
int mid = (begin + end)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left=sortedArrayToBSTHelper(nums, begin, mid-1);
root.right=sortedArrayToBSTHelper(nums,mid+1, end);
return root;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment