我的问题很简单。我正在尝试从树中删除具有以下结构的节点。如何删除符合条件的节点?基本上,我只想将其设置为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();
}
}
感谢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
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句