109. 有序链表转换二叉搜索树
class Solution(object):
# 题意要转成平衡二叉搜索树
# 先转成list,在转BST呗。
def sortedListToBST(self, head):
"""
:type head: ListNode
:rtype: TreeNode
"""
if not head:
return None
nums = []
while head:
nums.append(head.val)
head = head.next
return self.helper(nums)
def helper(self, nums):
if len(nums) == 0:
return None
mid = len(nums) // 2
root = TreeNode(nums[mid])
root.left = self.helper(nums[:mid])
root.right = self.helper(nums[mid + 1:])
return root