【问题标题】:Getting middle value of array to create balanced BST获取数组的中间值以创建平衡的 BST
【发布时间】: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


【解决方案1】:

您的递归没有正确编写,这就是问题所在。您应该始终添加中间元素,然后根据需要移动到左右部分。

那么让我们这样做吧:

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;
}

这打印 [7、3、1、0、2、5、4、6、11、9、8、10、13、12]

除了递归条件之外,您还可以看到我计算中间值的不同方式。通过计算int mid = (start + end) / 2;,您不会舍入该值而是截断它。因此,在您的情况下,中元素变为 6 而不是 7。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 2022-06-15
    • 2012-04-09
    • 1970-01-01
    • 2011-07-21
    相关资源
    最近更新 更多