一、數組構建普通的二叉排序樹
普通的二叉排序樹只需要保證二叉樹的根節點大於或等於其左子樹,根節點小於其右子樹即可,具體的算法代碼如下:
//數組構建一棵排序二叉樹
public static TreeNode createSortedTreeNode(TreeNode root,int next){
if (root == null){
root=new TreeNode(next);
return root;
}else {
if (next<=root.value){
root.left=createSortedTreeNode(root.left,next);
}else {
root.right=createSortedTreeNode(root.right,next);
}
}
return root;
}
二、數組構建高度最小的二叉排序樹
這裏只需要在(一)的基礎上保證根節點的左右子樹的高度<=1即可,利用二分查找算法
//數組建立一個高度最小的二叉排序樹
public static TreeNode createminheighttree(int[] array,int start, int end){
Arrays.sort(array);
if (array == null||array.length ==0){
System.out.println("數組爲空,無法構建二叉樹");
}
if (start > end){
return null;
}
int mid=start+(end - start)/2;
TreeNode root=new TreeNode(array[mid]);
root.left=createminheighttree(array, start, mid-1);
root.right=createminheighttree(array, mid+1,end);
return root;
}
三、主函數進行測試
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String line=sc.nextLine();
String[] array=line.split(",");
int[] nums=new int[array.length];
for (int i = 0; i < nums.length; i++) {
nums[i]=Integer.parseInt(array[i]);
}
//採用數組構建一顆排序二叉樹
if (array==null||array.length ==0){
throw new IllegalArgumentException("二叉樹構建失敗");
}
TreeNode root= new TreeNode(nums[0]);
for (int j = 1; j < nums.length; ++j) {
createSortedTreeNode(root,nums[j]);
}
midOrder(root);
System.out.println("採用數組構建一個高度最小排序二叉樹");
//採用數組構建一個高度最小排序二叉樹
TreeNode root1=createminheighttree(nums,0,nums.length-1);
midOrder(root1);
}