您的位置:首页 > 其它

Leetcode 108. Convert Sorted Array to Binary Search Tree

2017-01-20 10:45 501 查看
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return helper(0, nums.length-1, nums);
}

// requires a balanced binary search tree, every time choosing mid of the array as root
public static TreeNode helper(int low, int high, int[] nums) {
if (low > high) return null;

int mid = low + (high-low)/2;
TreeNode root = new TreeNode(nums[mid]);

root.left = helper(low, mid-1, nums);;
root.right = helper(mid+1, high, nums);;

return root;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: