My python solution_converted sorted listed to binary search tree_beat 80%

  • 0
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    def sortedArrayToBST(nums):
        n = len(nums)
        if not n:
            return None
        if n==1:
            return TreeNode(nums[0])
        n = len(nums)
        nodeVal = nums[(n-1)/2]
        hereNode = TreeNode(nodeVal)
        hereNode.left = sortedArrayToBST([i for i in nums if i<nodeVal])
        hereNode.right = sortedArrayToBST([i for i in nums if i>nodeVal])
        return hereNode
    class Solution(object):
        def sortedListToBST(self, head):
            :type head: ListNode
            :rtype: TreeNode
            # cheating by transfer list into an array 
            if not head:
                return None
            nums = []
            while head:
                head =
            return sortedArrayToBST(nums)

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.