[Leetcode]Convert Sorted List to Binary Search Tree

来源:互联网 发布:Python2.7图形编程 编辑:程序博客网 时间:2024/05/29 06:41

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

把一个有序的链表转换成一颗二分查找树 ~  刚开始用了一种比较naive的写法,虽然能AC,但是效率很慢,因为每次递归的时候都要遍历链表获得中间节点 ~  时间复杂度是O(NlogN), This is because each level of recursive call requires a total of N/2 traversal steps in the list, and there are a total of lg N number of levels (ie, the height of the balanced tree).  

class Solution:    # @param head, a list node    # @return a tree node    def sortedListToBST(self, head):        if head is None: return None        if head.next is None: return TreeNode(head.val)        fast, slow, prev = head, head, None        while fast != None and fast.next != None:            prev = slow            fast, slow = fast.next.next, slow.next        if prev != None:            prev.next = None        root = TreeNode(slow.val)        root.left = self.sortedListToBST(head)        root.right = self.sortedListToBST(slow.next)        return root


(*)然后参考了 http://leetcode.com/2010/11/convert-sorted-list-to-balanced-binary.html 的解法~ 思路是从下往上创建树的节点(bottom-up)~ 先对左子树进行递归,然后将当前结点作为根,迭代到下一个链表结点,最后再递归求出右子树。整体过程类似树的中序遍历~ 时间复杂度是O(n)

class Solution:    # @param head, a list node    # @return a tree node    def sortedListToBST(self, head):        if head is None: return None        curr, length = head, 0        while curr != None:            curr, length = curr.next, length + 1        self.head = head        return self.sortedRecur(0, length - 1)            def sortedRecur(self, start, end):        if start > end:            return None        mid = (start + end) / 2        left = self.sortedRecur(start, mid - 1)        root = TreeNode(self.head.val)        root.left = left        self.head = self.head.next        root.right = self.sortedRecur(mid + 1, end)        return root


0 0
原创粉丝点击