思路:
链表转数组,再递归
时间复杂度O(n)
空间复杂度O(n)
空了优化下,太慢了
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
# 为了方便找中点作为根,先转为列表存储
nums = []
while head:
nums.append(head.val)
head = head.next
# 定义转换函数
def helper(nums):
n = len(nums)
if n==0:return None
mid = n//2
root = TreeNode(nums[mid])
root.left = helper(nums[0:mid])
root.right = helper(nums[mid+1:])
return root
return helper(nums)