这道题是leetcode108的升级版,先将单链表转化成数组,然后再根据数组生成高度平衡二叉搜索树。
1 class Solution: 2 def sortedArrayToBST(self, nums: List[int]) -> TreeNode: 3 n = len(nums) 4 if n == 0: 5 return None 6 if n == 1: 7 return TreeNode(nums[0]) 8 mid = n // 2 9 root = TreeNode(nums[mid]) 10 root.left = self.sortedArrayToBST(nums[:mid]) 11 root.right = self.sortedArrayToBST(nums[mid+1:]) 12 return root 13 14 def sortedListToBST(self, head: ListNode) -> TreeNode: 15 lists = [] 16 while head != None: 17 lists.append(head.val) 18 head = head.next 19 root = self.sortedArrayToBST(lists) 20 return root