在Javascript中实现阵列备份的BST

在Javascript中实现阵列备份的BST,javascript,algorithm,binary-search-tree,Javascript,Algorithm,Binary Search Tree,我正在尝试使用数组实现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) {

我正在尝试使用数组实现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.array
看起来不正确。不确定我在哪里出错。

我还没有检查代码,但结果对我来说是正确的。 数组中的第一项是根。接下来的两个是秩1节点 接下来的4个节点是秩2节点。 接下来的8个节点是秩4节点 你的结果应该是


我觉得你的结果很正确。稀疏性的原因是,这是二叉树基于数组的支持结构的一个典型特征。如果树不完整,则会由于表示未填充子树的空元素而浪费条目。由于BST通常需要保持最佳的时间复杂度,因此基于链接节点的方法是典型的解决方案,这使得旋转和平衡更容易

通常,使用数组备份结构,其受益于内存布局和相对于堆分配的节点和指针的数组速度;堆操作不允许稀疏性,并且很容易在线性结构中使用您在这里使用的相同父子关系进行推理

话虽如此,您可以大大简化代码:

BST类{
构造函数(){
this.array=[];
}
插入(值,ix=0){
if(this.array[ix]==未定义){
this.array[ix]=值;
}
else if(值bst.insert(e));

console.log(bst.array)它有什么不正确的地方?您希望看到什么?
this.array=[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]