Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created 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/899830392d9457cb84193f78fbc4e767 to your computer and use it in GitHub Desktop.
Save vrat28/899830392d9457cb84193f78fbc4e767 to your computer and use it in GitHub Desktop.
Convert Sorted List to BST
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
curr, count = head, 0
while curr:
curr = curr.next
count += 1
def treeify(i: int, j: int) -> TreeNode:
if j < i: return None
mid, node = i + j >> 1, TreeNode()
node.left = treeify(i, mid - 1)
node.val, curr[0] = curr[0].val, curr[0].next
node.right = treeify(mid + 1, j)
return node
curr = [head]
return treeify(1, count)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment