Python solutions(not convert to array)


  • 0
    J
    class Solution(object):
        def sortedListToBST(self, head):
            """
            :type head: ListNode
            :rtype: TreeNode
            """
            if head is None:
                return None
            if head.next is None:
                return TreeNode(head.val)
    
            def find_mid(slow):
                fast, last = slow, None
                while fast is not None and fast.next is not None:
                    last, slow, fast = slow, slow.next, fast.next.next
                    
                last.next = None
                return slow
    
            mid = find_mid(head)
            root = TreeNode(mid.val)
            root.left, root.right = self.sortedListToBST(head), self.sortedListToBST(mid.next)
            
            return root
    

Log in to reply
 

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