2018-10-09 leetcode Convert Sorted Array to Binary Search Tree Convert Sorted Array to Binary Search TreeRecursive 递归版本 1234567891011121314151617181920# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def sortedArrayToBST(self, nums): """ :type nums: List[int] :rtype: TreeNode """ if not nums: return None i = len(nums) / 2 node = TreeNode(nums[i]) node.left = self.sortedArrayToBST(nums[:i]) node.right = self.sortedArrayToBST(nums[i+1:]) return node test code 123456789101112131415161718Given the sorted array: [-10,-3,0,5,9],One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5In [1]: class TreeNode(object): ...: def __init__(self, x): ...: self.val = x ...: self.left = None ...: self.right = None ...:In [42]: s = Solution(); t = s.sortedArrayToBST([-10,-3,0,5,9]) Iteratively 非递归版本 12345678910111213141516171819202122# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def sortedArrayToBST(self, nums): """ :type nums: List[int] :rtype: TreeNode """ def helper(left, right): if left > right: return None idx = (left + right) / 2 node = TreeNode(nums[idx]) node.left = helper(left, idx - 1) node.right = helper(idx + 1, right) return node return helper(0, len(nums) - 1) test code 123456789101112131415161718Given the sorted array: [-10,-3,0,5,9],One possible answer is: [0,-10,5,null,-3,null,9] 0 / \ -10 5 \ \ -3 9In [1]: class TreeNode(object): ...: def __init__(self, x): ...: self.val = x ...: self.left = None ...: self.right = None ...:In [58]: s = Solution(); t = s.sortedArrayToBST([-10,-3,0,5,9]) leet code Newer Kth Smallest Element in a Sorted Matrix Older Kth Smallest Element in a BST