[英]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.
但是有沒有一種有效的方法可以從未排序的數組中輕松創建平衡的二進制搜索樹,而無需更改數組/復制數組等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.