Solution in Python


  • 0
    V

    '''
    class Solution(object):
    def sortedArrayToBST(self, nums):
    """
    :type nums: List[int]
    :rtype: TreeNode
    """
    if not nums:
    return None
    length = len(nums)
    middle = length / 2
    root = TreeNode(nums[middle])
    if middle > 0:
    left_list = nums[0:middle]
    else:
    left_list = []
    if middle+1 < length:
    right_list = nums[middle+1:length]
    else:
    right_list = []
    if left_list or right_list:
    self.getChildNote(root,left_list,right_list)
    return root
    def getChildNote(self,node,left_list,right_list):
    if left_list:
    temp_length = len(left_list)
    temp_middle = temp_length / 2
    temp_child_note = TreeNode(left_list[temp_middle])
    node.left = temp_child_note
    if temp_middle > 0:
    temp_l_list = left_list[0:temp_middle]
    else:
    temp_l_list = []
    if temp_middle+1 < temp_length:
    temp_r_list = left_list[temp_middle + 1:temp_length]
    else:
    temp_r_list = []
    if temp_l_list or temp_r_list:
    self.getChildNote(temp_child_note,temp_l_list,temp_r_list)
    if right_list:
    temp_length = len(right_list)
    temp_middle = temp_length / 2
    temp_child_note = TreeNode(right_list[temp_middle])
    node.right = temp_child_note
    if temp_middle > 0:
    temp_l_list = right_list[0:temp_middle]
    else:
    temp_l_list = []
    if temp_middle+1 < temp_length:
    temp_r_list = right_list[temp_middle + 1:temp_length]
    else:
    temp_r_list = []
    if temp_l_list or temp_r_list:
    self.getChildNote(temp_child_note,temp_l_list,temp_r_list)
    '''


Log in to reply
 

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