Swift solution


  • 0
    class Solution {
        func sortedArrayToBST(_ nums: [Int]) -> TreeNode? {
            if nums.count == 0 {
                return nil
            }
            
            return helper(nums, 0, nums.count - 1)
        }
        
        func helper(_ nums: [Int], _ low: Int, _ high: Int) -> TreeNode? {
            if low > high {
                return nil
            }
            
            let middle = (low + high) / 2
            let node = TreeNode(nums[middle])
            node.left = helper(nums, low, middle - 1)
            node.right = helper(nums, middle + 1, high)
            
            return node
        }
    }
    

Log in to reply
 

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