【发布时间】:2018-05-08 09:14:08
【问题描述】:
我正在尝试查找数组的中间元素或索引,然后获取每一半的中间,依此类推...
所以假设我们有[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:将插入到的树
代码:
public static BST fillBST(BST b, List<Integer> nums, int start, int end) {
int mid = (start + end) / 2;
if (start > end)
b.insertt(nums.get(mid));
else {
fillBST(b, nums, start, mid - 1);
fillBST(b, nums, mid + 1, end);
}
return 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
【问题讨论】:
-
对不起,代码没有格式化,我试过了,但在发布格式化时遇到了一些问题。
-
您只会插入最后一个值(在退出条件或递归调用中)。那是你的问题。
标签: java arrays sorting arraylist binary-search-tree