Convert Sorted Array to Binary Search Tree
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 sortedArrayToBST(int[] num) {
if(num==null||num.length==0)
{
return null;
}
int len=num.length;
int mid=len/2;
TreeNode root=new TreeNode(num[mid]);
bst(root,num,0,mid-1,true);
bst(root,num,mid+1,len-1,false);
return root;
}
public void bst(TreeNode root,int[] a,int s,int e,boolean isLeft)
{
if(s>e)
{
return;
}
int mid=(s+e)/2;
TreeNode node=new TreeNode(a[mid]);
if(isLeft)
{
root.left=node;
bst(node,a,s,mid-1,true);
bst(node,a,mid+1,e,false);
}
else
{
root.right=node;
bst(node,a,s,mid-1,true);
bst(node,a,mid+1,e,false);
}
}
}