题目: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.
入门recursion的初级题目。解题思路:利用递归思想去解决,首先找到有序数组的中位数节点,即位于最中间位置的节点作为根节点,然后依次递归建立左右子树。
递归三要素:
- 递归的定义:
这里需要三个参数:nums,初始位置,结束位置。 - 递归的拆解:
去一个中间点,左边一部分,右边一部分,把活儿分给交给左右两边,一层一层吩咐下去。 - 递归的出口:
若start大于end,则可以继续构建二叉搜索树,如果不满足则停止。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private TreeNode buildTree(int[]nums,int start,int end){
if (start>end){
return null;
}
TreeNode result = new TreeNode(nums[(start+end)/2]);
result.left=buildTree(nums, start, (start+end)/2-1);
result.right=buildTree(nums, (start+end)/2+1,end);
return result;
}
public TreeNode sortedArrayToBST(int[] nums) {
if(nums==null||nums.length==0){
return null;
}
return buildTree(nums,0,nums.length-1);
}
}