https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/
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
time: o(n) space: o(height)
pre order: 先弄自己, 再管下面的兄弟
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null || nums.length ==0 )return null ;
int left = 0, right = nums.length -1 ;
return helper(nums, left, right);
}
//everytime create the root and connect to left and right
private TreeNode helper(int[] nums, int left, int right) {
int mid = left + (right - left) /2 ;
TreeNode node = new TreeNode(nums[mid]) ;
if (mid+ 1<=right){
node.right = helper(nums, mid+1, right) ;
}
if (mid -1 >= left){
node.left = helper(nums, left, mid-1) ;
}
//going down and repeat
return node ;
}