Last updated 10 months ago
Was this helpful?
time: O(n), must visit all nums element
space: O(n), must build all nums element, O(logn) for recursion stack, because use binary search idea
class Solution { public TreeNode sortedArrayToBST(int[] nums) { return helper(nums, 0, nums.length - 1); } private TreeNode helper(int[] nums, int left, int right) { if (left > right) return null; int mid = left + (right - left)/2; TreeNode node = new TreeNode(nums[mid]); node.left = helper(nums, left, mid - 1); node.right = helper(nums, mid + 1, right); return node; } }