My code:
/**
* 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 || nums.length == 0)
return null;
return getBST(0, nums.length - 1, nums);
}
private TreeNode getBST(int begin, int end, int[] nums) {
if (begin > end)
return null;
else if (begin == end)
return new TreeNode(nums[begin]);
int mid = (begin + end) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = getBST(begin, mid - 1, nums);
root.right = getBST(mid + 1, end, nums);
return root;
}
}
My test result:
这道题目和上面的一个想法.具体就不细说了。
**
总结: sorted array -> balanced bst
**
Anyway, Good luck, Richardo!
My code:
/**
* 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 || nums.length == 0) {
return null;
}
return helper(nums, 0, nums.length - 1);
}
private TreeNode helper(int[] nums, int begin, int end) {
if (begin > end) {
return null;
}
else if (begin == end) {
return new TreeNode(nums[begin]);
}
int middle = begin + (end - begin) / 2;
TreeNode root = new TreeNode(nums[middle]);
root.left = helper(nums, begin, middle - 1);
root.right = helper(nums, middle + 1, end);
return root;
}
}
简单题,没什么好说的。
Anyway, Good luck, Richardo! -- 08/16/2016