因为数组是有序,数组的中间节点就是根节点,这样数组就可以分为2个部分,左子树和右子树
分析:本题考察二叉搜索树的建树方法,简单的递归结构。关于树的算法设计一定要联想到递归,因为树本身就是递归的定义。而,学会把递归改称非递归也是一种必要的技术。毕竟,递归会造成栈溢出,关于系统底层的程序中不到非不得以最好不要用。但是对某些数学问题,就一定要学会用递归去解决。
/**
* Created by renshuang on 10/14/13.
*/
public class TestConverTree {
public static void main(String args[]){
int[] array={1,2,3,4,5};
TestConverTree tree=new TestConverTree();
tree.printMid(tree.arrayConvertBst(array,0,array.length-1));
}
public void printMid(Node node){
if(node.left!=null){
printMid(node.left);
}
System.out.println(node.data);
if(node.right!=null){
printMid(node.right);
}
}
public Node arrayConvertBst(int[] data,int start,int end){
if(start>end){
return null;
}
int mid=(start+end)/2;
Node current=new Node(data[mid]);
current.left=arrayConvertBst(data,start,mid-1);
current.right=arrayConvertBst(data,mid+1,end);
return current;
}
class Node {
int data;
Node left;
Node right;
public Node(){
}
public Node(int data){
this.data=data;
}
public Node(int data,Node left,Node right){
this.data=data;
this.left=left;
this.right=right;
}
}
}