Leetcode 109.有序链表转换二叉搜索树(Convert Sorted List to Binary Search Tree)

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

1 题目描述(Leetcode题目链接

  给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

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

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

      0
     / \
   -3   9
   /   /
 -10  5

2 题解

  递归实现,根据二叉搜索树的性质,每次递归时将链表的中点当做当前根节点,其次当前根节点的左孩子等于链表左半边的中点,右孩子等于链表右半边的中点。这时候就需要用到快慢指针来分割链表。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def cut(self, head):
        if not head.next:
            return None, head, None
        pre, slow, fast = head, head, head
        while fast and fast.next:
            fast = fast.next.next
            pre = slow
            slow = slow.next
        right = slow.next
        mid = slow
        pre.next = None
        return head, mid, right

    def sortedListToBST(self, head: ListNode) -> TreeNode:
        if not head:
            return None
        left, mid, right = self.cut(head)
        root = TreeNode(mid.val)
        if left:
            root.left = self.sortedListToBST(left)
        if right:
            root.right = self.sortedListToBST(right)
        return root
发布了264 篇原创文章 · 获赞 63 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_39378221/article/details/105091786