LeetCode 108 Convert Sorted Array to Binary Search Tree
My solution is too long compared with the official solution. I wonder why it does not work. I tried to “print(root1.val)”, but the result is None. Any comment on my thinking process is welcome (Either modifying my code or telling me why I should not do the code)
def sortedArrayToBST_with_root(nums, root):
n = len(nums)
#if not nums:
if n == 0:
root = Node(None)
# return
elif n == 1:
root = Node(None)
root.val = nums[0]
# return
elif n == 2:
root = Node(None)
root.val = nums[1]
root.left = Node(nums[0])
# return
else:
mid = (n-1)//2
root = Node(nums[mid])
nums_left_half = nums[:mid]
nums_right_half = nums[(mid+1):]
root.left = Node(None)
root.right = Node(None)
sortedArrayToBST_with_root(nums_left_half, root.left)
sortedArrayToBST_with_root(nums_right_half, root.right)
def sortedArrayToBST(nums):
root = Node(None)
sortedArrayToBST_with_root(nums, root)
return root
nums = [-10,-3,0,5,9]
root1 = sortedArrayToBST(nums)
print(root1.val)