Python Solution with recursion


  • 0
    class Solution(object):
        def sortedListToBST(self, head):
            if not head:
                return None
            prev = None
            fast_runner = slow_runner = head
            while fast_runner.next and fast_runner.next.next:
                prev = slow_runner
                fast_runner = fast_runner.next.next
                slow_runner = slow_runner.next
            root = TreeNode(slow_runner.val)
            if prev:
                prev.next = None
            else:
                head = None
            root.left = self.sortedListToBST(head)
            root.right = self.sortedListToBST(slow_runner.next)
            return root
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.