把已经排好序的数组,重塑成平衡二叉树,直接利用递归的思想做即可
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
static TreeNode root = null;
public TreeNode sortedArrayToBST(int[] num) {
// TreeNode root = null;
root = buildBST(num, 0, num.length - 1, root);
return root;
}
public static TreeNode buildBST(int[] num, int low, int height, TreeNode node){
if(low == height){
return new TreeNode(num[low]);
}
else if(low < height){
int mid = (low + height) / 2;
node = new TreeNode(num[mid]);
node.left = buildBST(num, low, mid - 1, node.left);
node.right = buildBST(num, mid + 1, height, node.right);
return node;
}
else return null;
}
}