Python solution with detailed explanation

  • 0


    Convert Sorted List to Binary Search Tree


    • Design a split method that returns the left list, root, and right list.
    class Solution(object):
        def split(self, head):
            slow = head
            fast =
            if fast:
                fast =
                return None, head, None
            while fast and
                slow =
                fast =
                if fast:
                    fast =
            second =
   = None
            root = second
            second =
   = None
            return head, root, second
        def sortedListToBST(self, head):
            if head == None:
                return None
            head, root, second = self.split(head)
            tnode = TreeNode(root.val)
            tnode.left = self.sortedListToBST(head)
            tnode.right = self.sortedListToBST(second)
            return tnode

Log in to reply

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