108. Convert Sorted Array to Binary Search Tree

Posted on Feb 24, 2025

Solution

Time: O(N), Space: O(1)

Implementation

class Solution {
    fun sortedArrayToBST(nums: IntArray): TreeNode? {
        if (nums.isEmpty()) return null
        val m = nums.size / 2
        return TreeNode(nums[m]).also {
            it.left = sortedArrayToBST(nums.copyOfRange(0, m))
            it.right = sortedArrayToBST(nums.copyOfRange(m + 1, nums.size))
        }
    }
}