Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created March 17, 2020 08:11
Show Gist options
  • Save RP-3/f0735dbaa553f5ded42160b0ea3617f8 to your computer and use it in GitHub Desktop.
Save RP-3/f0735dbaa553f5ded42160b0ea3617f8 to your computer and use it in GitHub Desktop.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
if head == None:
return None
leftTail, mid = self.middleNode(head)
root = TreeNode(mid.val)
rightHead = mid.next # head of right half
mid.next = None # break list into two
leftTail.next = None # break root off left half
root.left = self.sortedListToBST(head) if leftTail.val != mid.val else None
root.right = self.sortedListToBST(rightHead)
return root
def middleNode(self, head: ListNode) -> (ListNode, ListNode):
slow = head
fast = head
beforeSlow = head
while fast.next:
beforeSlow = slow
slow = slow.next
fast = fast.next
if fast.next:
fast = fast.next
return (beforeSlow, slow)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment