108. Convert Sorted Array to Binary Search Tree (Easy)
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
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 5
Solutions
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null || nums.length == 0) {
return null;
}
return add(nums, 0, nums.length - 1);
}
private TreeNode add(int[] nums, int start, int end) {
// check out if overstep the boundary
if (start > end || start < 0 || start >= nums.length || end < 0 || end >= nums.length) {
return null;
}
// if only 1 element left in the array
if (start == end) {
return new TreeNode(nums[start]);
}
// find the medium and create a new node as local root node
int middle = (start + end) / 2;
int medium = nums[middle];
TreeNode root = new TreeNode(medium);
// split the array into two sections and creates corresponding TreeNodes.
root.left = add(nums, start, middle - 1);
root.right = add(nums, middle + 1, end);
return root;
}
}