原文:
Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height.
译文:
给定一个有序数组(递增),写程序构建一棵具有最小高度的二叉树。
思路:因为是有序的数组,所以直接提取中数为root,然后递归建立其左子树和右子树
package Tree_Graph;
import CtCILibrary.TreeNode;
public class S4_3 {
// 递归把有序数组转为BST
public static TreeNode createMinBST(int[] A, int start, int end) {
if ( start > end ) {
return null;
}
int mid = (start + end) / 2;
TreeNode root = new TreeNode(A[mid]);
root.left = createMinBST(A, start, mid-1);
root.right = createMinBST(A, mid+1, end);
return root;
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// We needed this code for other files, so check out the code in the library
TreeNode root = TreeNode.createMinimalBST(array);
System.out.println("Root? " + root.data);
System.out.println("Created BST? " + root.isBST());
System.out.println("Height: " + root.height());
}
}