Skip to content

Instantly share code, notes, and snippets.

@vrat28
Last active May 6, 2021 14:51
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/f80e6f7d5b09c32b9d65ae35b3244de9 to your computer and use it in GitHub Desktop.
Save vrat28/f80e6f7d5b09c32b9d65ae35b3244de9 to your computer and use it in GitHub Desktop.
class Solution {
var current:ListNode?
func sortedListToBST(_ head: ListNode?) -> TreeNode? {
var count = 0
var curr: ListNode? = head
while curr != nil {
count += 1
curr = curr?.next
}
current = head
let rootNode = partition_helper(1,count)
return rootNode
}
func partition_helper(_ left: Int, _ right:Int) -> TreeNode? {
guard left <= right else { return nil}
let mid = left + (right - left ) / 2
let node = TreeNode()
// Inorder : Left -> Root -> Right
node.left = partition_helper(left, mid - 1)
node.val = current!.val
// Move the list pointer
current = current?.next
node.right = partition_helper(mid + 1, right)
return node
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment