好开心,我终于独立完成了!!!!
class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if len(nums)==0: return None i=len(nums)//2 root=TreeNode(nums[i]) root.left=self.sortedArrayToBST(nums[:i]) root.right=self.sortedArrayToBST(nums[i+1:]) return root
执行用时 :88 ms, 在所有 python3 提交中击败了77.09%的用户
内存消耗 :16.3 MB, 在所有 python3 提交中击败了5.59%的用户
——2019.11.15
再次复习:
public TreeNode sortedArrayToBST(int[] nums) { int len = nums.length; if(len == 0){ return null; } int i = len/2; TreeNode root = new TreeNode(nums[i]); root.left = sortedArrayToBST(nums,0,i-1); root.right = sortedArrayToBST(nums,i+1,len-1); return root; } private TreeNode sortedArrayToBST(int[] nums, int start, int end) { int n = end - start + 1; if(n == 0){ return null; } int i = n/2; TreeNode node = new TreeNode(nums[start +i]); node.left = sortedArrayToBST(nums,start,start +i-1); node.right = sortedArrayToBST(nums,start + i + 1,end); return node; }
——2020.7.2