【LeetCode 中等題】52-有序連結串列轉二叉搜尋樹
阿新 • • 發佈:2019-01-08
題目描述:給定一個單鏈表,其中的元素按升序排序,將其轉換為高度平衡的二叉搜尋樹。本題中,一個高度平衡二叉樹是指一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過 1。
示例:
給定的有序連結串列: [-10, -3, 0, 5, 9], 一個可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面這個高度平衡二叉搜尋樹: 0 / \ -3 9 / / -10 5
解法1。連結串列有序,說明是中序遍歷的結果,利用快慢指標找到連結串列中點,然後切斷左和中點-右的聯絡,每次遞迴找子鏈的中點,注意邊界條件。思路和從有序連結串列裡構建二叉樹是一樣的思路。
class Solution(object): def sortedListToBST(self, head): """ :type head: ListNode :rtype: TreeNode """ if not head: return if not head.next: return TreeNode(head.val) root_node = self.findRoot(head) root = TreeNode(root_node.val) root.left = self.sortedListToBST(head) root.right = self.sortedListToBST(root_node.next) return root def findRoot(self, head): if not head or not head.next: return head fast = head slow = head pre = head while fast and fast.next: pre = slow slow = slow.next fast = fast.next.next pre.next = None return slow