Convert Sorted List to Binary Search Tree

medium

Question

加一個(gè)升序鏈列轉(zhuǎn)化為height balanced BST

Solution

此題與Convert Sorted Array to Binary Search Tree有序數(shù)列構(gòu)建BST非常類似,但是有序數(shù)列變成了有序鏈列。

第一個(gè)方法當(dāng)然是把鏈列轉(zhuǎn)化為數(shù)列再套用上面的方法。

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

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

class Solution(object):
    def sortedListToBST(self, head):
        """
        :type head: ListNode
        :rtype: TreeNode
        """
        ls = []
        p = head
        while p:
            ls.append(p.val)
            p = p.next
            
        return self.helper(ls)
    
    def helper(self, ls):
        try:
            mid = len(ls)/2
            root = TreeNode(ls[mid])
            root.left = self.helper(ls[:mid])
            root.right = self.helper(ls[mid+1:])
            return root
        except:
            return None

由于需要先轉(zhuǎn)化,如果要求不能轉(zhuǎn)化呢。現(xiàn)在考慮直接從鏈列入手。下面的算法使用兩個(gè)指針,一快一慢,來(lái)找到鏈列的中間值。處理方法與有序數(shù)列類似。

class Solution(object):
    def sortedListToBST(self, head):
        """
        :type head: ListNode
        :rtype: TreeNode
        """
        if not head:
            return 
        if not head.next:
            return TreeNode(head.val)
        dummy = ListNode(0)
        dummy.next = head
        slow, fast = dummy, head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        root = TreeNode(slow.next.val)
        root.right = self.sortedListToBST(slow.next.next)
        slow.next = None
        root.left = self.sortedListToBST(head)
        return root

上面的方法是top-down的,time complexity為O(n*logn). 下面看一個(gè)bottom-up的approach,這樣可以依照順序利用鏈列。top-down的方法經(jīng)常需要重復(fù)計(jì)算,這個(gè)時(shí)候bottom-up是應(yīng)該考慮的option。

class Solution(object):
    def sortedListToBST(self, head):
        """
        :type head: ListNode
        :rtype: TreeNode
        """
        n = 0
        p = head
        self.node = head
        while p:
            n += 1
            p = p.next
        return self.helper(0, n-1)
    
    def helper(self, start, end):
        if start > end:
            return None
        mid = (start+end)/2
        l = self.helper(start,mid-1)
        root = TreeNode(self.node.val)
        root.left = l
        self.node = self.node.next
        root.right = self.helper(mid+1,end)
        return root
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容