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.
Example:
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(Binary Search Tree)其定义:
1 首先它也是一个二叉树,故满足递归定义;
2 其次每个节点只存在一个值;
3 需满足左子树值<=根值<=右子树,故按照中序遍历会得到一个非递减序列。
这道题直接参考了网上的思路,大家用的都是递归的方法
解题思路:从递归出发,但是要结合二叉查找树的定义,每次将数组二分中间值作为根节点,依次递归二分并将中间值赋值给根节点,最后返回根结点,递归返回的临界条件是:左索引大于右索引
//主体部分是从数组的两端向中间扫描,每次都新建mid值为根节点,并指定左区间的下一轮返回mid值为其左节点,指定右区间的下一轮返回mid值为其右节点。
class Solution {
public TreeNode sortedArrayToBST(int[] num) {
return buildTree(num,0,num.length-1);//迭代
}
public TreeNode buildTree(int[] num, int low, int high){
if(low>high)//递归终止条件为左索引大于右索引,不包括等于以免遗漏元素,只有最后一层的叶子节点中可以存在null空元素
return null;
int mid = (low+high)/2;//二分法的中间节点是两端点的平均值,如果为1.5则int之后取1
TreeNode node = new TreeNode(num[mid]);//新建mid值为根节点
node.left = buildTree(num,low,mid-1);//根节点的左节点,是来自下一轮针对左区间递归的mid值
node.right = buildTree(num,mid+1,high);//根节点的右节点,是来自下一轮针对右区间递归的mid值
return node;//子函数返回值为node节点,每一次调用的时候都会返回,因此会自上而下,从中间向两侧的建立起二叉树
}
}