题目描述
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。
代码:
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 l, int r)
{
if(l>r)
return null;
int m = (l+r)/2;
TreeNode root = new TreeNode(num[m]);
root.left = helper(num,l,m-1);
root.right = helper(num,m+1,r);
return root;
}