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

来源:互联网 发布:凯立德端口修改工具 编辑:程序博客网 时间:2024/06/03 19:10

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 = rightclass 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)

原创粉丝点击