簡體   English   中英

是否可以從未排序的數組中高效地創建平衡的二進制搜索樹而無需對數組進行排序?

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

標題說明了一切。

我看到我可以很容易地從一個未排序的數組中創建一個二進制搜索樹。

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)

當然,您將無法以更快的速度完成此操作,因為那樣的話,您實際上僅使用比較就可以對數組進行o(n log n)排序, 這是不可能的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM