1、递归法
class Solution(object):
def sortedArrayToBST(self,nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if nums == [] or nums == None:
return None
return self.buildTree(nums, 0, len(nums)-1)
def buildTree(self, nums, start, end):
if start > end:
return None
middle = (start + end)//2
root = TreeNode(nums[middle])
root.left = self.buildTree(nums, start, middle-1)
root.right = self.buildTree(nums, middle+1, end)
return root
2、非递归法
class Solution(object):
def sortedArrayToBST(self,nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if nums ==[] or nums == None:
return None
root = TreeNode(0)
stack = [[0, len(nums)-1, root]]
while(len(stack)):
left,right, node = stack.pop()
middle = (left + right)//2
node.val = nums[middle]
if left <= middle-1:
node.left = TreeNode(0)
stack.append([left, middle-1, node.left])
if right >= middle+1:
node.right = TreeNode(0)
stack.append([middle+1, right, node.right])
return root
参考博客:https://blog.csdn.net/dpengwang/article/details/87906431