Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 6, 2021 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrat28/6041b0c440aeb2bb9f58a93c9fe8fddb to your computer and use it in GitHub Desktop.
Save vrat28/6041b0c440aeb2bb9f58a93c9fe8fddb to your computer and use it in GitHub Desktop.
LinkedList to Binary Search Tree
class Solution {
func sortedListToBST(_ head: ListNode?) -> TreeNode? {
var sortedList = [Int]()
var current:ListNode? = head
while let node = current {
sortedList.append(node.val)
current = node.next
}
let rootNode = partition_helper(sortedList, 0, sortedList.count - 1)
return rootNode
}
func partition_helper(_ list:[Int], _ left: Int, _ right:Int) -> TreeNode? {
guard left <= right else { return nil}
let mid = left + (right - left ) / 2
let node = TreeNode(list[mid])
node.left = partition_helper(list, left, mid - 1)
node.right = partition_helper(list,mid + 1, right)
return node
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment