简体   繁体   English

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

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

The title says it all. 标题说明了一切。

I see that I can create a binary search tree out of an unsorted array rather easily. 我看到我可以很容易地从一个未排序的数组中创建一个二进制搜索树。

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;

And can also create a balanced binary search tree out of an ordered array easily. 并且还可以轻松地从有序数组中创建平衡的二进制搜索树。

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.

But is there an efficient way to create a balanced binary search tree from an unsorted array just as easily without changing the array / copying the array, ect. 但是有没有一种有效的方法可以从未排序的数组中轻松创建平衡的二进制搜索树,而无需更改数组/复制数组等。

Your second approach is likely to be the simplest of all if you have no libraries at hand. 如果您手边没有任何库,则第二种方法可能是最简单的方法。 It's also very efficient if you use a good sorting algorithm (asymptotically optimal with a very low constant factor). 如果使用良好的排序算法(渐进优化且常数因子非常低),它也非常有效。

Your first approach is not really efficient, because the tree can become unbalanced. 您的第一种方法并不是真正有效,因为树可能变得不平衡。 You can however insert all elements into a self-balancing binary search tree one by one, in any order. 但是,您可以按任意顺序将所有元素一一插入到自平衡二进制搜索树中。 This also needs time O(n log n) , like the second approach. 像第二种方法一样,这也需要时间O(n log n)

Of course you won't be able to do it faster than that, because then you would have essentially sorted the array in o(n log n) using only comparisons, which is impossible . 当然,您将无法以更快的速度完成此操作,因为那样的话,您实际上仅使用比较就可以对数组进行o(n log n)排序, 这是不可能的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM