Convert Sorted Array to Binary Search Tree
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:Idea
Code
public TreeNode sortedArrayToBST(int[] nums) {
return fill(0, nums.length-1, nums);
}
public TreeNode fill(int low, int high, int[] nums){
if(low>high){
return null;
}
int mid = (low+high)/2;
TreeNode root = new TreeNode(nums[mid]);
if(low==high){
return root;
}
root.left = fill(low, mid-1, nums);
root.right = fill(mid+1, high, nums);
return root;
}Last updated
