有序链表转换二叉搜索树
- 难度: 中等
- 通过率: 38.7%
- 题目链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
题目描述
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定的有序链表: [-10, -3, 0, 5, 9], 一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树: 0 / \ -3 9 / / -10 5
解法:
快慢指针找到链表的中点,使用两个指针限制左右子树的链表范围。不要将原链表断开,有副作用。
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
return self._list_to_BST(head, None)
def list_to_BST(self, start, end):
if start == end:
return None
fast = start
slow = start
while fast and fast.next and fast != end and fast.next != end:
fast = fast.next.next
slow = slow.next
root = TreeNode(slow.val)
root.left = self.list_to_BST(start, slow)
root.right = self.list_to_BST(slow.next, end)
return root