Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 是否可以从未排序的数组中高效地创建一个平衡的二叉搜索树,而无需对数组进行排序?_Java_C++_Arrays_Algorithm_Tree - Fatal编程技术网

Java 是否可以从未排序的数组中高效地创建一个平衡的二叉搜索树,而无需对数组进行排序?

Java 是否可以从未排序的数组中高效地创建一个平衡的二叉搜索树,而无需对数组进行排序?,java,c++,arrays,algorithm,tree,Java,C++,Arrays,Algorithm,Tree,标题说明了一切 我发现我可以很容易地从一个未排序的数组中创建一个二叉搜索树 If root is null, set 1st array value to the root current = root for each value in the array: while current not null If arrays value >= current value if root.left is null, set array value to cu

标题说明了一切

我发现我可以很容易地从一个未排序的数组中创建一个二叉搜索树

If root is null, set 1st array value to the root
current = root
for each value in the array:
  while current not null
     If arrays value >= current value
          if root.left is null, set array value to current.right
          else current = current.right and continue
     Else if arrays value < current value
          if current.left is null, set array value to current.left
          else current = current.left
return root;

但是,有没有一种有效的方法可以从未排序的数组创建一个平衡的二叉搜索树,而无需更改数组/复制数组等

如果手头没有库,那么第二种方法可能是最简单的方法。如果使用良好的排序算法(具有非常低的常数因子的渐近最优),它也非常有效

您的第一种方法并不真正有效,因为树可能变得不平衡。 但是,您可以按任何顺序将所有元素逐个插入到中。这也需要时间O(n logn),就像第二种方法一样


当然,您不能比这更快地完成此操作,因为这样您基本上只需要使用比较就可以在o(n log n)中对数组进行排序。

应该注意的是,如果OP意味着自己实现此操作,那么这肯定不像从已排序的数组创建平衡的BST那么容易。实现一个自平衡的BST是很棘手的。@Heuster:不过,有人@Heuster:可能会像排序一样,OP似乎没有实现themselves@NiklasB. 第一种方法不适用于平衡的bst,它只是一个示例,演示了如何轻松地将数组转换为bst(我想这是毫无意义的)。谢谢,自我平衡二叉树就是我想要的答案。它不会操纵数组,仍然会返回一个平衡的bst。
Get the Middle of the array and make it root.
Recursively do same for left half and right half.
      Get the middle of left half and make it left child of the root created in step 1.
      Get the middle of right half and make it right child of the root created in step 1.