测试用例[-10,-3,0,5,9],前面是我的写法,返回结果是[]
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if not nums:
return None
else:
middle = len(nums)//2
root =TreeNode(nums[middle])
root.left=self.sortedArrayToBST(nums[0:middle])
root.right=self.sortedArrayToBST(nums[middle+1:len(nums)])
return root
后面是路人的写法,可以 AC
class Solution:
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None
else:
mid=len(nums)//2
tn=TreeNode(nums[mid])
nums1=nums[0:mid]
nums2=nums[mid+1:len(nums)]
tn.left=self.sortedArrayToBST(nums1)
tn.right=self.sortedArrayToBST(nums2)
return tn
感觉很奇怪啊,不知道为什么