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

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

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

示例:

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

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

      0
     / \
   -3   9
   /   /
 -10  5

1.找到序列的中点作为根,前半部分作为左子树,后半部分作为右子树,然后递归的处理,缺点:链表操作比较复杂

2.首先将链表转换成列表,然后递归处理

3.快慢指针找中点

class Solution:
    def sortedListToBST(self, head: ListNode) -> TreeNode:
        if not head:return None
        if not head.next:return TreeNode(head.val)
        mid_len=0
        tmp=head
        #统计链表的长度
        while tmp:
            mid_len+=1
            tmp=tmp.next
        pre=None
        head_keep=head
        #在中点出切分
        for i in range(mid_len//2):
            pre=head
            head=head.next
        pre.next=None

        newhead=TreeNode(head.val)
        newhead.left=self.sortedListToBST(head_keep)
        newhead.right=self.sortedListToBST(head.next)
        return newhead

class Solution:
    def sortedListToBST(self, head):
        if not head:
            return head
        res = []
        while head:
            res.append(head.val)
            head = head.next
        def build(l):
            if not l:
                return None
            mid = len(l)//2
            root = TreeNode(l[mid])
            root.left = build(l[:mid])
            root.right = build(l[mid+1:])
            return root
        return build(res)

class Solution:
    def sortedListToBST(self, head: ListNode) -> TreeNode:
        def findMid(head,tail):
            slow=fast=head
            while fast!=tail and fast.next!=tail:
                slow=slow.next
                fast=fast.next.next
            return slow
        def helper(head,tail):
            if head==tail:return 
            mid_node=findMid(head,tail)
            root=TreeNode(mid_node.val)
            root.left=helper(head,mid_node)
            root.right=helper(mid_node.next,tail)
            return root
        return helper(head,None)

 

你可能感兴趣的:(Leetcode)