题目描述:
给出一个升序排序的数组,将其转化为平衡二叉搜索树(BST).
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
对于此问题,将高度平衡的二叉树定义为一个二叉树,其中每个节点的两个子树的深度相差不超过1。
例:
Given 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 5
主要思想:
把一个有序数组转化为一棵二叉搜索树,二叉搜索树(BST)具有以下性质:
- 若其左子树存在,则其左子树中每个节点的值都不大于该节点值;
- 若其右子树存在,则其右子树中每个节点的值都不小于该节点值。
示例:
因此,可以用递归来构建一棵二叉搜索树,每次把数组分为两半,把数组中间的值作为其父节点,然后把数组的左右两部分进行递归,继续构造其左右子树。
实现代码:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
if ((num == null) || (num.length == 0)) {
return null;
}
return helper(num, 0, num.length - 1);
}
private TreeNode helper(int[] num, int left, int right) {
if (left > right) {
return null;
}
int mid = (left + right + 1) >> 1;
TreeNode node = new TreeNode(num[mid]);
node.left = helper(num, left, mid - 1);
node.right = helper(num, mid + 1, right);
return node;
}
}
注意:在牛客网上的环境下,mid = (left + right + 1) / 2,如果没有 +1,不能通过所有的测试样例;