LeetCode打卡: 109. 有序链表转换二叉搜索树

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

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

示例:
LeetCode打卡: 109. 有序链表转换二叉搜索树_第1张图片

链接:https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
解题思路:
法一:先遍历有序列表,将其转化为有序数组,再将有序数组转化为BST。
我的代码:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def sortedListToBST(self, head):
        """
        :type head: ListNode
        :rtype: TreeNode
        """
        # 先用数组存储链表中的值,在将有序数组转化为平衡BST
        arr = []
        p = head
        while p:
            arr.append(p.val)
            p = p.next
        
        return self.arrToBST(arr)
    
    def arrToBST(self, arr):
        if arr:
            mid = len(arr)//2
            root = TreeNode(arr[mid])
            root.left = self.arrToBST(arr[:mid])
            root.right = self.arrToBST(arr[mid + 1:])
            return root
        else:
            return None

Time: O(N)
Space: O(N)

法二:利用BST的中序遍历是有序序列的原理,反过来按照中序遍历的顺序生成BST。
我的代码:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def sortedListToBST(self, head):
        """
        :type head: ListNode
        :rtype: TreeNode
        """
        size = 0
        p = head
        while p:
            size += 1
            p = p.next
        self.node = head  //全局变量
        return self.convert(1, size)
    
    def convert(self, l, r):
        if l > r:
            return None
        mid = (l + r) // 2
        left = self.convert(l, mid - 1)
        root = TreeNode(self.node.val)
        root.left = left
        self.node = self.node.next
        root.right = self.convert(mid + 1, r)
        return root

Time: O(N)
Space: O(logN)

你可能感兴趣的:(LeetCode打卡)