TreeviewCopyright © aleen42 all right reserved, powered by aleen42
02. 最小高度树
https://leetcode-cn.com/problems/minimum-height-tree-lcci/
Java
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length == 0) return null;
TreeNode root = new TreeNode(nums[nums.length / 2]);
root.left = sortedArrayToBST(Arrays.copyOfRange(nums, 0, nums.length / 2));
root.right = sortedArrayToBST(Arrays.copyOfRange(nums, nums.length / 2 + 1, nums.length));
return root;
}
}
Python
'''
Author: Goog Tech
Date: 2020-09-11 08:40:19
LastEditTime: 2020-09-11 08:41:44
Description: https://leetcode-cn.com/problems/minimum-height-tree-lcci/
FilePath: \leetcode-googtech\面试题04\#02. 最小高度树\Solution.py
WebSite: https://algorithm.show/
'''
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums: return None
mid = len(nums) // 2
root = TreeNode(nums[mid])
root.left = self.sortedArrayToBST(nums[:mid])
root.right = self.sortedArrayToBST(nums[mid + 1:])
return root