Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
解题思路:使用二叉搜索树的方式遍历数组,每次遍历数组中间节点为子树的根节点,递归遍历找出中间节点。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode search(int[] num,int left,int right){
TreeNode node=null;
int index=-1;
if(left>right){
return null;
}
index=(right+left)/2;
node=new TreeNode(num[index]);
if(index+1<=right){
node.right=search(num,index+1,right);
}
if(index-1>=left){
node.left=search(num,left,index-1);
}
return node;
}
public TreeNode sortedArrayToBST(int[] num) {
int left=0;
int right=num.length-1;
TreeNode root=null;
if(num==null||right<0){
return root;
}
root=search(num,left,right);
return root;
}
}