描述
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
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.
给一个递增数组,造出来一个平衡二叉树
平衡二叉树=二叉搜索树(左子树都比根小,右子树都比根大)+左右子树高度不超过1
例子
思路
- 递归
对于每个结点,从递增数组中取中间值【可以是选择中间偏左,或中间偏右作为根节点都可以】作为其值,然后将该数组分为两部分,分别采用递归的方法构建左右子树
答案
- python
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if len(nums)==0:
return None
m = int(len(nums)/2)
root = TreeNode(nums[m])
root.left = self.sortedArrayToBST(nums[0:m])
root.right = self.sortedArrayToBST(nums[m+1:len(nums)])
return root
- java
import java.util.Arrays;
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
//如果数组为空,返回null
if (nums.length==0)
return null;
int m = nums.length/2;
TreeNode root = new TreeNode(nums[m]);
//Arrays.copyOfRange会创建新数组,导致时间上会慢,不如直接采用使用原数组,只修改[start:end]
root.left = sortedArrayToBST(Arrays.copyOfRange(nums, 0, m));
root.right = sortedArrayToBST(Arrays.copyOfRange(nums, m+1, nums.length));
return root;
//只修改start:end方法,不新建数组 更快:可以是选择中间偏左,或中间偏右作为根节点都可以
public TreeNode sortedArrayToBST(int[] nums) {
return insert(nums, 0, nums.length-1);
}
public TreeNode insert(int[] nums, int start, int end)
{
if (start>end)
return null;
int m = (start+end)/2;
TreeNode root = new TreeNode(nums[m]);
root.left = insert(nums, start, m-1);
root.right = insert(nums, m+1, end);
return root;
}