题目:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
题意:
将一个有序的数组转化为二叉查找树
解题思路:
这题和上一题convert-sorted-list-to-binary-search-tree这题差不多
还是找出数组中点,以该中点为根
然后依次递归构造左右子树就行
这里需要注意的是
左子树递归范围是 (0,mid-1)不包括mid
右子树递归范围是(mid+1,num.length)
中点的确认:mid = (head+end)/2;
mid = (head+end+1)/2;
这两个都行,但是牛客网的判断只有第二个
代码:
public TreeNode sortedArrayToBST(int[] num) {
if(num == null || num.length <= 0) {
return null;
}
return createTree(0,num.length-1,num);
}
public TreeNode createTree(int head,int end,int [] num) {
if(head > end) {
return null;
}
int mid = (head+end)/2;
TreeNode root = new TreeNode(num[mid]);
root.left = createTree(head,mid-1,num);
root.right = createTree(mid+1,end,num);
return root;
}