Last active
October 31, 2018 20:52
-
-
Save BrianLitwin/ef3949aecc6bf6bc8c5a84da4c1be764 to your computer and use it in GitHub Desktop.
Array -> Binary Search Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
func sortedArrayToBST(_ nums: [Int]) -> TreeNode? { | |
return makeBST(nums, 0, nums.count - 1) | |
} | |
func makeBST(_ nums: [Int], _ start: Int, _ end: Int) -> TreeNode? { | |
guard start <= end else { return nil } | |
let mid = (start + end) / 2 | |
let node = TreeNode(nums[mid]) | |
node.left = makeBST(nums, start, mid - 1) | |
node.right = makeBST(nums, mid + 1, end) | |
return node | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment