Simple Clear One Method Java Solution


  • 0
    Y

    By using Arrays.copyOfRange to pass a new array to the method recursively.
    Simply control the length of the passing array: if noms.length < 1 then return null.
    This simple if can apply to any input situation.

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

Log in to reply
 

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