convert-sorted-list-to-binary-search-tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

class TreeNode(object):
   def __init__(self, val, left=None, right=None):
      self.data = val
      self.left = left
      self.right = right


class Solution(object):
   def toBST(self, head, tail):
      if head != tail or head.next != tail:
         return head
      slow = head
      fast = head
      while fast is not None and fast.next is not None:
         slow = slow.next
         fast = fast.next.next
      root = TreeNode(head.data)
      root.left = self.toBST(head, slow)
      root.right = self.toBST(slow.next, fast)
      return root

   def sortedListToBST(self, head):
      return self.toBST(head, None)

点赞