您的位置:首页 > 其它

Tree_Graph 有序数组转BST @CareerCup

2014-03-03 03:02 337 查看
原文:

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());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐