6-lines Java Accepted Solution


  • 5
    J

    The idea is making the middle element as root and recursively calling the method until the length of the array is zero.

    public class Solution {
            public TreeNode sortedArrayToBST(int[] nums) {
                if(nums.length==0)return null;
                int ptr=nums.length/2;
                TreeNode root=new TreeNode(nums[ptr]);
                root.left=sortedArrayToBST(Arrays.copyOfRange(nums,0,ptr));
                root.right=sortedArrayToBST(Arrays.copyOfRange(nums,ptr+1,nums.length));
                return root;
            }
        }

  • 0
    J

    Does Arrays.copyOfRange create a new array?


  • 0
    J

    Yes, it does


  • 0
    L

    The only problem is extra space used. you can solve this by using another function which has two index for the array. :)


  • 0
    R

    Excellent readability, at a cost of O(nlgn) extra space.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.