【发布时间】: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