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

140 阅读1分钟

题目地址(109. 有序链表转换二叉搜索树)

leetcode-cn.com/problems/co…

题目描述

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

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

示例:

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

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

      0
     / \
   -3   9
   /   /
 -10  5

思路

通过快慢指针获取到链路中点,然后抽取出来创建二叉树,再通过递归把链路一分为二逐层递归

关键点

代码

  • 语言支持:Python3

Python3 Code:


# Definition for singly-linked list.
# 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 head == None:
            return head
        #快慢指针
        pre, slow, fast = None, head, head
        while fast and fast.next:
            fast = fast.next.next
            pre = slow#pre作为slow【中点】左边的指针存在
            slow = slow.next
        if pre:
            pre.next = None#把链路从中间断开
        rootTreeNode = TreeNode(slow.val)
        if fast == slow:
            return rootTreeNode
        rootTreeNode.left = self.sortedListToBST(head)
        rootTreeNode.right = self.sortedListToBST(slow.next)
        return rootTreeNode

复杂度分析

令 n 为数组长度。

  • 时间复杂度:O(nlogn)O(nlogn)
  • 空间复杂度:O(n)O(n)