JAVA solution simple recursion beats 98.68% solutions


  • 0
    A
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution 
    {
        public TreeNode sortedArrayToBST(int[] nums) 
        {
            if(nums == null || nums.length < 1)
                return null;
            else if(nums.length == 1)
                return new TreeNode(nums[0]);
            else
                return createBST(nums, 0, nums.length - 1);
        }
        
        private TreeNode createBST(int[] nums, int L, int R)
        {
            if(L > R || L < 0 || R >= nums.length)
                return null;
            else if(L == R)
                return new TreeNode(nums[L]);
            else
            {
                int mid = L + (R - L) / 2;
                TreeNode leftNode = createBST(nums, L, mid - 1);
                TreeNode rightNode = createBST(nums, mid + 1, R);
                
                TreeNode node = new TreeNode(nums[mid]);
                node.left = leftNode;
                node.right = rightNode;
                
                return node;
            }
        }
    }
    

Log in to reply
 

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