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
posted @ 2020-09-13 14:51  人间烟火地三鲜  阅读(141)  评论(0编辑  收藏  举报