leetcode_109 有序链表转换二叉搜索树

369 阅读1分钟

要求

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

示例:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

      0
     / \
   -3   9
   /   /
 -10  5

核心代码

# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sortedListToBST(self, head: ListNode) -> TreeNode:
        if not head:
            return None
        l = list()
        while head:
            l.append(head.val)
            head = head.next
        def sortedArrayToBST(nums):
            if not nums:
                return None
            def dfs(start,end):
                if end < start:
                    return
                mid = (end + start) //2
                root = TreeNode(nums[mid])
                root.left = dfs(start,mid-1)
                root.right = dfs(mid+1,end)
                return root
            return dfs(0,len(nums)-1)
        return sortedArrayToBST(l)

另一解法

# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sortedListToBST(self, head: ListNode) -> TreeNode:
        if not head:
            return None
        if not head.next:
            return TreeNode(head.val)
        slow ,fast = head,head
        pre = head
        while fast and fast.next:
            pre = slow
            slow = slow.next
            fast = fast.next.next
        pre.next = None
        part1 = head
        part2 = slow.next
        root = TreeNode(slow.val)
        root.left = self.sortedListToBST(part1)
        root.right = self.sortedListToBST(part2)
        return root

image.png

解题思路:第一种解法:和我们上一道题中,leetcode_108 通过升序列表还原一棵平衡搜索二叉树是一样的,我们可以先将有序列表变成一个有序array,在沿用上一题的代码,就可以完成构建了;第二种解法:在这个解法中,我们使用的是快慢指针的方式来查找中值,并且将得到左右两个新链表,我们可以使用递归的方式,完成左右子树的构建。