1 """ 2 Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 3 For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 4 Example: 5 Given the sorted array: [-10,-3,0,5,9], 6 One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 7 0 8 / 9 -3 9 10 / / 11 -10 5 12 """ 13 """ 14 对于二叉搜索树,左右结点的值有规律,应该想到递归 15 二分+递归解法 16 """ 17 class TreeNode: 18 def __init__(self, x): 19 self.val = x 20 self.left = None 21 self.right = None 22 23 class Solution: 24 def sortedArrayToBST(self, nums): 25 return self.convert(nums, 0, len(nums) - 1) 26 27 def convert(self, nums, left, right): 28 if left > right: # bug 没写这个判断maximum recursion depth exceeded 29 return None 30 mid = (left + right) // 2 31 Node = TreeNode(nums[mid]) 32 Node.left = self.convert(nums, left, mid - 1) 33 Node.right = self.convert(nums, mid + 1, right) 34 return Node