My accepted Java solution with O(N) time


  • 0
    W
     public class Solution {
        int i;
        public TreeNode sortedArrayToBST(int[] nums) {
            if(nums == null) {
                return null;
            }
            i = 0;
            int len = nums.length;
            return sortHelper(len, nums);
            
        }
        public TreeNode sortHelper(int size, int[] nums) {
            if(size <= 0) {
                return null;
            }
            TreeNode left = sortHelper(size / 2, nums);
            TreeNode root = new TreeNode(nums[i]);
            i++;
            TreeNode right = sortHelper(size - 1 - size / 2, nums);
            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.