[Lintcode]106. Convert Sorted List to Binary Search Tree/[Leetcode]109. Convert Sorted List to Binary Search Tree

106. Convert Sorted List to Binary Search Tree/109. Convert Sorted List to Binary Search Tree

  • 本题难度: Medium/Medium
  • Topic: Linked List

Description

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

Example

                     2
1->2->3  =>   / \
                     1   3

我的代码

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next

Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param: head: The first node of linked list.
    @return: a tree node
    """
    def sortedListToBST(self, head):
        def buidBST(begin, end, p = ListNode(0)):
            if begin>end:
                return None,p
            mid = math.ceil(begin + (end-begin)/2)
            leftchild,p = buidBST(begin,mid-1,p)
            root = TreeNode(p.val)
            root.left = leftchild
            p = p.next
            rightchild,p = buidBST(mid+1,end,p)
            root.right = rightchild
            if root.right == None:
                right=-6
            else:
                right = root.right.val
            if root.left == None:
                left=-6
            else:
                left = root.left.val
            return root,p

        if head is None:
            return None
        l = 0
        pos = head
        while(head):
            head = head.next
            l += 1
        return buidBST(0,l-1, pos)[0]

思路

因为一开始没思路,所以参考了一个O(n)的代码Share my O(1) space and O(n) time Java code这是Java的代码,改成python遇到了很大的问题。
主要是p我实在没找到合适的使用全局变量的方法,最后把p作为参数传递。
其次是应该上取整才能优先右子树。

  • 时间复杂度
  • 出错
    忘了把左右儿子结点加上去了,后来又忘记移动p了
posted @ 2019-02-14 15:10  siriusli  阅读(75)  评论(0编辑  收藏  举报