Created
May 6, 2021 14:51
-
-
Save vrat28/899830392d9457cb84193f78fbc4e767 to your computer and use it in GitHub Desktop.
Convert Sorted List to BST
This file contains 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: | |
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