Java 获取数组的中间值以创建平衡BST

Java 获取数组的中间值以创建平衡BST,java,arrays,sorting,arraylist,binary-search-tree,Java,Arrays,Sorting,Arraylist,Binary Search Tree,我试图找到数组的中间元素或索引,然后得到每一半的中间,依此类推。。。 假设我们有[0,1,2,3,4,5,6,7,8,9,10,11,12,13] 我所期望的7,3,1,0,2,5,4,6… 这样,当我从新数组中添加元素时,我会得到一个平衡的BST 开始:开始索引(0) 结束:长度-1 nums:要添加的数字列表 b:将插入到的树 代码: 公共静态BST fillBST(BST b,列表nums,int start,int end){ int mid=(开始+结束)/2; 如果(开始>结束)

我试图找到数组的中间元素或索引,然后得到每一半的中间,依此类推。。。 假设我们有
[0,1,2,3,4,5,6,7,8,9,10,11,12,13]

我所期望的
7,3,1,0,2,5,4,6…

这样,当我从新数组中添加元素时,我会得到一个平衡的BST

  • 开始:开始索引(0)
  • 结束:长度-1
  • nums:要添加的数字列表
  • b:将插入到的树
代码:

公共静态BST fillBST(BST b,列表nums,int start,int end){
int mid=(开始+结束)/2;
如果(开始>结束)
b、 insertt(nums.get(mid));
否则{
fillBST(b,nums,start,mid-1);
fillBST(b,nums,mid+1,end);
}
返回b;
}

输出我使用列表
[0,31]:0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31得到的结果
您的递归编写不正确,这就是问题所在。您应该始终添加中间元素,然后根据需要移动到左右部分

让我们这样做:

public static void main(String[] args) {
    List<Integer> list = Arrays.asList(new Integer[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 });
    List<Integer> res =new ArrayList<>();
    fillBST(res, list, 0, list.size() - 1);
    System.out.println(res);
}

public static List<Integer> fillBST(List<Integer> b, List<Integer> nums, int start, int end) {
    int mid = (int)Math.round((1.0 * start + end) / 2);
    b.add(nums.get(mid));
    if (start <= mid - 1)
        fillBST(b, nums, start, mid - 1);
    if (end >= mid + 1)
        fillBST(b, nums, mid + 1, end);
    return b;
}
publicstaticvoidmain(字符串[]args){
List=Arrays.asList(新的整数[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13});
List res=new ArrayList();
fillBST(res,list,0,list.size()-1);
系统输出打印项次(res);
}
公共静态列表fillBST(列表b、列表nums、int start、int end){
int mid=(int)数学圆((1.0*开始+结束)/2);
b、 添加(nums.get(mid));
如果(开始=中间+1)
fillBST(b,nums,mid+1,end);
返回b;
}
这张照片 [7,3,1,0,2,5,4,6,11,9,8,10,13,12]


除了递归条件,您可以看到我计算mid的不同方式。通过计算它
intMID=(开始+结束)/2不舍入值,而是截断值。因此,在您的情况下,medium元素将变为6而不是7。

很抱歉,代码没有格式化,我尝试过,但在将其格式化后遇到了一些问题。您将只插入最后的值(在退出条件或递归调用中)。那是你的问题。
public static void main(String[] args) {
    List<Integer> list = Arrays.asList(new Integer[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 });
    List<Integer> res =new ArrayList<>();
    fillBST(res, list, 0, list.size() - 1);
    System.out.println(res);
}

public static List<Integer> fillBST(List<Integer> b, List<Integer> nums, int start, int end) {
    int mid = (int)Math.round((1.0 * start + end) / 2);
    b.add(nums.get(mid));
    if (start <= mid - 1)
        fillBST(b, nums, start, mid - 1);
    if (end >= mid + 1)
        fillBST(b, nums, mid + 1, end);
    return b;
}