【问题标题】:Javascript BST recursion. How to remove a node class with "this" reference?Javascript BST 递归。如何使用“this”引用删除节点类?
【发布时间】:2018-12-14 15:58:25
【问题描述】:

我的问题很简单。我正在尝试使用以下结构从我的树中删除一个节点。如何删除符合我条件的节点?基本上我只想将它设置为 null,因此它的父级只是指向 null。

这不是实际代码,而是解释概念。基本上树中的每个节点都是一个新的 BST。

class BST{
  constructor(val){
    this.val = val;
    this.right;
    this.left;
  }

  insert(val){
     // find correct node insert in appropriate child
     this.left = new BST(val) // or this.right
  }

  someRecursiveFn(){

    if(this.val === 'removeMe') {
      // REMOVE NODE
      // this = null // illegal
      // this.val = null // same problem...I still have the class prototype & it's right & left children

      return
    }

    this.left.someRecursiveFn();
  }
}

【问题讨论】:

  • 我不确定,但我认为这是不可能的,除非您将对象的实例存储在对象本身中(例如使用单例模式)。因为类本身不知道它的存储位置。
  • 你能检查this 的孩子而不是检查this 本身吗? if(this.left.val === 'removeMe') this.left = null;this.right 相同?
  • 单身和检查孩子都可以工作。但我只是好奇是否有可能保持这个干净,同时避免将参数传递给函数。好像不是……

标签: javascript binary-search-tree


【解决方案1】:

“优雅地”解决该问题的一种方法是引入一个特殊的终端对象,该对象将用于代替 null 来指定值的缺失。

class Zero {
    insert(val) {
        return new Node(val)
    }
    remove(val) {
        return null
    }
}

let zero = () => new Zero()

class Node {
    constructor(val) {
        this.val = val
        this.L = zero()
        this.R = zero()
    }
    insert(val) {
        if(val < this.val) this.L = this.L.insert(val)
        if(val > this.val) this.R = this.R.insert(val)
        return this
    }
    remove(val) {
        if(val === this.val)
            return zero()

        if(val < this.val) this.L = this.L.remove(val)
        if(val > this.val) this.R = this.R.remove(val)
        return this
    }
}

//

tree = new Node(5)
tree.insert(2)
tree.insert(6)
tree.insert(3)
tree.insert(8)
tree.insert(4)
tree.insert(7)


document.write('<xmp>' + JSON.stringify(tree, 0, 4) + '</xmp>')

tree.remove(4)

document.write('<xmp>' + JSON.stringify(tree, 0, 4) + '</xmp>')

tree.remove(8)

document.write('<xmp>' + JSON.stringify(tree, 0, 4) + '</xmp>')

【讨论】:

    【解决方案2】:

    感谢 georg 提出这个想法。这真的很简单。只需在递归调用上使用赋值操作即可。

    class BST{
      constructor(val){
        this.val = val;
        this.right;
        this.left;
      }
    
      insert(val){
         // find correct node insert in appropriate child
         this.left = new BST(val) // or this.right
      }
    
      someRecursiveFn(){
    
        if(this.val === 'removeMe') {
          // REMOVE NODE
          // this = null // illegal
          // this.val = null // same problem...I still have the class prototype & it's right & left children
    
          return null;
        }
    
        this.left = this.left.someRecursiveFn();
    
        return this
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-12-23
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      相关资源
      最近更新 更多