是否有可能从未排序的数组中高效地创建平衡二叉搜索树而不对数组进行排序?

Is it possible to efficiently create a balanced binary search tree from an unsorted array without sorting the array?

本文关键字:排序 数组 搜索树 创建 有可能 是否 高效 平衡      更新时间:2023-10-16

标题说明了一切。

我看到我可以创建一个二叉搜索树的无序数组相当容易。

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;

并且还可以轻松地从有序数组中创建平衡二叉搜索树。

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.

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

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

你的第一种方法并不是很有效,因为树会变得不平衡。然而,您可以将所有元素以任意顺序一个接一个地插入到自平衡二叉搜索树中。与第二种方法一样,这也需要时间O(n log n)

当然你不可能做得比这更快,因为那样的话你实际上是在 0 (n log n)中对数组进行排序,只使用比较,这是不可能的