leetcode-109-有序链表转二叉搜索树

---恢复内容开始---

 题目描述:

 

 方法一:O(n) O(n)

class Solution:
    def sortedListToBST(self, head: ListNode) -> TreeNode:
        nums = []
        while head:
            nums.append(head.val)
            head = head.next
        def helper(nums):
            if not nums:
                return None
            m = len(nums)//2
            root = TreeNode(nums[m])
            root.left = helper(nums[0:m])
            root.right = helper(nums[m+1:])
            return root
        return helper(nums)

方法二:O(nlogn)O(logn)

class Solution:
    def findMid(self,head):
        prevPtr = None
        slowPtr = head
        fastPtr = head
        while fastPtr and fastPtr.next:
            prevPtr = slowPtr
            slowPtr = slowPtr.next
            fastPtr = fastPtr.next.next
        if prevPtr:
            prevPtr.next = None
        return slowPtr
    def sortedListToBST(self, head: ListNode) -> TreeNode:
        if not head:
            return None
        mid = self.findMid(head)
        node = TreeNode(mid.val)
        if head==mid:
            return node
        node.left = self.sortedListToBST(head) 
        node.right = self.sortedListToBST(mid.next) 
        return node

 

---恢复内容结束---

猜你喜欢

转载自www.cnblogs.com/oldby/p/11185354.html
0条评论
添加一条新回复