AC Python 88ms simple recursion

  • 0
    def _toBST(self, nums, l, r):
        if l == r:
            return None
        m = (l + r) >> 1
        root = TreeNode(nums[m])
        root.left = self._toBST(nums, l, m)
        root.right = self._toBST(nums, m + 1, r)
        return root
    def sortedArrayToBST(self, nums):
        return self._toBST(nums, 0, len(nums))
    # 32 / 32 test cases passed.
    # Status: Accepted
    # Runtime: 88 ms
    # 99.30%

    The logic is almost the same as a post order traversal of a binary tree. We need to build the left and right subtree before we can connect them to the root.

Log in to reply

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