我正在尝试使用数组实现 bst,但没有成功:
class BST {
constructor() {
this.array =[]
this.rootSet = false;
this.index = 0
}
getLeft(index) {
return (2 * index) + 1
}
getRight(index) {
return 2 * (index + 1)
}
getParent(index) {
return index >>> 1
}
insert(value) {
if (!this.rootSet) {
this.rootSet = true
this.array = [value]
this.index++;
} else {
// inserts recursively.
this.insertHelper(this.getParent(0), value);
}
}
// helper function to insert recursively.
insertHelper(index, value) {
if (value < this.array[index] && this.array[this.getLeft(index)] === undefined) {
this.array[this.getLeft(index)] = value
} else if (value >= this.array[index] && this.array[this.getRight(index)] === undefined) {
this.array[this.getRight(index)] = value
} else {
if (value < this.array[index]) {
this.insertHelper(this.getLeft(index), value);
} else {
this.insertHelper(this.getRight(index), value);
}
}
}
}
我尝试了以下内容:
a.insert(2)
a.insert(0)
a.insert(3)
a.insert(10)
a.insert(30)
a.array // [2, 0, 3, empty × 3, 10, empty × 7, 30]
a.array看起来不正确。不知道我在哪里犯了错误。
POPMUISE
叮当猫咪
相关分类