用有序数组构建高度最低的BST

##用有序数组构建高度最低的BST

package _8题;
/**
 * Given a sorted (increasing order) array,
 * write an algorithm to create a binary search tree with minimal height.
 */
import _8题.TreeNode;
public class _3BSTWithMinHeight {
     
   TreeNode createMinBst(int[]arr) {
     
	   return createMinBst(arr,0,arr.length-1);
  
   }
private TreeNode createMinBst(int[] arr, int start, int end) {
     
	// TODO Auto-generated method stub
	if(start>end)return null;
	int mid =start+((end-start)>>1);
	TreeNode left =createMinBst(arr,start,mid-1);
	TreeNode right =createMinBst(arr,mid+1,end);
	TreeNode res =new TreeNode(arr[mid]);
	res.left= left;
	res.right=right;
	return res;
}  
public static void main(String[] args) {
     
	_3BSTWithMinHeight obj = new _3BSTWithMinHeight();
    int[] arr = {
     1, 2, 3, 4, 5, 6, 7};
    TreeNode minBst = obj.createMinBst(arr);
    System.out.println(minBst);
  }
}

package _8题;

public class TreeNode<T> {
     
public T val;
public TreeNode<T>left=null;
public TreeNode<T>right=null;
public TreeNode<T>parent=null;
public TreeNode(T val) {
     
	this.val = val;
}

}

你可能感兴趣的:(数据结构之树,数据模板,java,算法)