Java recursive solution


  • 0
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode sortedArrayToBST(int[] nums) {
            if(nums.length == 0) {
                return null;
            }
            return sortedArrayToBST(nums, 0, nums.length);
        }
        public TreeNode sortedArrayToBST(int[] nums, int start, int end) {
            if(end <= start) {
                return null;
            } else if(end - start == 1) {
                return new TreeNode(nums[start]);
            }
            int mid = start + (end - start) / 2;
            TreeNode node = new TreeNode(nums[mid]);
            node.left = sortedArrayToBST(nums, start, mid);
            node.right = sortedArrayToBST(nums, mid + 1, end);
            return node;
        }
    }
    

Log in to reply
 

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