108. Convert Sorted Array to Binary Search Tree / 109. Convert Sorted List to Binary Search Tree
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null) return null;
return helper(nums, 0, nums.length - 1);
}
private TreeNode helper(int[] nums, int start, int end) {
if (start > end) return null;
TreeNode node = new TreeNode(nums[(start + end) / 2]);
node.left = helper(nums, start, (start + end) / 2 - 1);
node.right = helper(nums, (start + end) / 2 + 1, end);
return node;
}
}Last updated