LeetCode – 108. Convert Sorted Array to Binary Search Tree

題目連結: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

其他人寫的解答: https://zxi.mytechroad.com/blog/tree/leetcode-108-convert-sorted-array-to-binary-search-tree/

// Test cases:
// nums: []
// nums: [1,2,3]
// nums: [1,2,3,4] 
    func sortedArrayToBST(_ nums: [Int]) -> TreeNode? {
        return build(0, nums.count - 1, nums)
    }

    func build(_ left: Int, _ right: Int, _ nums: [Int]) -> TreeNode? {
        if left <= right {
            let m = left + (right - left) / 2
            let node = TreeNode(nums[m])
            node.left = build(left, m - 1, nums)
            node.right = build(m + 1, right, nums)
            return node
        } 
        return nil
    }