My 0ms Accepted Java Solution

  • 0

    Hi,everyone, I think this solution is really simple. The intuition of my solution is using half of the array and construct a subtree each time. Hope it helps.

    public class Solution {
        public TreeNode sortedArrayToBST(int[] nums) {
            if(nums==null || nums.length==0)    return null;
            return toBST(nums,0,nums.length-1);
        private TreeNode toBST(int[]nums,int i, int j)
            if(i>j) return null;
            if(i==j)    return new TreeNode(nums[i]);
            int mid=i+(j-i)/2;
            TreeNode root=new TreeNode(nums[mid]);
            TreeNode left=toBST(nums,i,mid-1);
            TreeNode right=toBST(nums,mid+1,j);
            return root;

Log in to reply

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