Python recursive


  • 0

    '''
    def sortedArrayToBST(self, nums):
    if len(nums) == 0:
    return None
    index = int(len(nums) / 2)
    root = TreeNode(nums[index])
    if index - 1 >= 0:
    self.dfs("left", 0, index - 1, nums, root)
    if index + 1 < len(nums):
    self.dfs("right", index + 1, len(nums) - 1, nums, root)
    return root

    def dfs(self, dir, begin, end, nums, root):
        if dir == "left":
            index = int((end + begin) / 2)
            root.left = TreeNode(nums[index])
            if begin <= index - 1:
                self.dfs("left", begin, index - 1, nums, root.left)
            if end >= index + 1:
                self.dfs("right", index + 1, end, nums, root.left)
        else:
            index = int((end + begin) / 2)
            root.right = TreeNode(nums[index])
            if begin <= index - 1:
                self.dfs("left", begin, index - 1, nums, root.right)
            if end >= index + 1:
                self.dfs("right", index + 1, end, nums, root.right)

Log in to reply
 

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