Question: https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Question Name: Convert Sorted Array to Binary Search Tree
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param num, a list of integers # @return a tree node def sortedArrayToBST(self, num): ''' With a given array num, the root of the corresponding tree is always the middle one in the array. ''' treeSize = len(num) if treeSize == 0: return None else: root = TreeNode(num[treeSize//2]) root.left = self.sortedArrayToBST(num[:treeSize//2]) root.right = self.sortedArrayToBST(num[treeSize//2+1:]) return root |