[英]Slow Binary Search Tree Insertion
我一直在創建一些數據結構來保持我的技能敏銳。 我創建了一個 BST,並一直在對陣列的速度進行壓力測試。 我注意到 BST 的插入速度比 array.push 慢得多。 我一直在使用 Math.random 並向這兩種數據結構添加數百萬個數字。 奇怪的是,BST 在查找值方面比 array.includes/indexOf 快得多。 有沒有更好的方法來編碼我的插入 function 或者只是用 BST 插入一個緩慢的部分
這是我的代碼
insert(data) {
if(this.root === null) {
this.root = new Node(data)
return this
}
let current = this.root
while(current) {
if(current.data === data) {
console.log(data + ' Already exists in tree')
return
}
if(data < current.data) {
if(current.left === null) {
current.left = new Node(data)
this.size++
return this
}
current = current.left
}
if(data > current.data) {
if(current.right === null) {
current.right = new Node(data)
this.size++
return this
}
current = current.right
}
}
}
您的代碼非常好。
TL;DR:您的比較/性能基准不准確
我的回答假設您熟悉算法時間測量的大 O 表示法,如果您沒有在評論中這么說,我將編輯我的答案。
問題是, array.push
是一個簡單的操作,因為它總是將元素附加到數組的末尾,這需要O(1)
(常數)時間,而將元素插入 BST 意味着您正在尋找正確的位置要插入它,因為它必須按順序排列,所以不要像使用array,push
那樣將它放在樹的末尾。 這個操作需要更多的時間( O(logn)
其中n
是樹中的節點數,准確地說),所以如果你比較這兩個,當然array.push
會更快。
如果您嘗試將一個元素按順序插入到數組中,它會比將其插入到 BST 中慢得多,因為您必須搜索數組中的每個元素,直到找到正確的位置,然后移動所有內容將新元素放入數組中,這需要O(n)
時間,其中n
是數組中的元素數。
因此,總而言之,BST excel用於按順序查找和插入元素,當順序無關緊要並且您可以將元素放在任何地方時,數組通常會更快,這就是為什么在您的 BST 中搜索比includes
或數組的indexOf
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.