Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created August 7, 2017 02:45
Show Gist options
  • Select an option

  • Save cixuuz/ce94283cac108b12166bd9ca0aec5459 to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/ce94283cac108b12166bd9ca0aec5459 to your computer and use it in GitHub Desktop.
[108. Convert Sorted Array to Binary Search Tree] #leetcode
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums.length == 0) return null;
return helper(nums, 0, nums.length-1);
}
public TreeNode helper(int[] nums, int start, int end) {
if (start > end) return null;
int mid = (end - start) / 2 + start;
TreeNode left = helper(nums, start, mid-1);
TreeNode right = helper(nums, mid+1, end);
TreeNode node = new TreeNode(nums[mid]);
node.left = left;
node.right = right;
return node;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment