Ejemplo n.º 1
0
 def sorted_list_to_bst(left, right):
     if left > right:
         return None
     mid = left + (right - left) // 2
     left_node = sorted_list_to_bst(left, mid - 1)
     new_node = TreeNode(self.__class__.head.val)
     new_node.left = left_node
     self.__class__.head = self.__class__.head.next
     new_node.right = sorted_list_to_bst(mid + 1, right)
     return new_node
Ejemplo n.º 2
0
 def sorted_list_to_bst(left, right):
     if left > right:
         return None
     mid = left + (right-left)//2
     left_node = sorted_list_to_bst(left, mid-1)
     new_node = TreeNode(self.__class__.head.val)
     new_node.left = left_node
     self.__class__.head = self.__class__.head.next
     new_node.right = sorted_list_to_bst(mid+1, right)
     return new_node
Ejemplo n.º 3
0
 def sortedArrayToBST(self, nums):
     """
     :type nums: List[int]
     :rtype: TreeNode
     """
     if not nums:
         return None
     mid = len(nums)//2
     node = TreeNode(nums[mid])
     node.left = self.sortedArrayToBST(nums[:mid])
     node.right = self.sortedArrayToBST(nums[mid+1:])
     return node