Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
一刷
题解:recursion, 思路很简单
/**
* 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 == null) return null;
return sortedArrayToBST(nums, 0, nums.length-1);
}
private TreeNode sortedArrayToBST(int[] nums, int start, int end){
if(start<0 || end>nums.length-1) return null;
if(start>end) return null;
int mIndex = start + (end-start)/2;
TreeNode root = new TreeNode(nums[mIndex]);
root.left = sortedArrayToBST(nums, start, mIndex-1);
root.right = sortedArrayToBST(nums, mIndex+1, end);
return root;
}
}
二刷
recursion
/**
* 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) {
return sortedArrayToBST(nums, 0, nums.length-1);
}
public TreeNode sortedArrayToBST(int[] nums, int lo, int hi){
if(hi<lo) return null;
int mid = lo + (hi - lo)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = sortedArrayToBST(nums, lo, mid-1);
root.right = sortedArrayToBST(nums, mid+1, hi);
return root;
}
}