https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
这道题和108差不多,就是数组改成了LikedList,转化一下就可以了。

func sortedListToBST(_ head: ListNode?) -> TreeNode? {
    var lNode = head
    var arr = [Int]()
    while let n = lNode {
        arr.append(n.val)
        lNode = n.next
    }
    return sortedArrayToBST(arr)
}
func sortedArrayToBST(_ nums: [Int]) -> TreeNode? {
    guard !nums.isEmpty else { return nil }
    guard nums.count > 1 else { return TreeNode(nums[0]) }
    let mid = nums.count/2
    let root = TreeNode(nums[mid])
    root.left = sortedArrayToBST(Array(nums[0..<mid]))
    root.right = sortedArrayToBST(Array(nums[mid+1..<nums.count]))
    return root
}

5E904542-A463-43C5-8EDA-E508B1B7226F