javascript - Javascript BST 递归。如何使用“this”引用删除节点类?
问题描述
我的问题真的很简单。我正在尝试使用以下结构从我的树中删除一个节点。如何删除符合我条件的节点?基本上我只想将它设置为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();
}
}
解决方案
一种“优雅地”解决这个问题的方法是引入一个特殊的终端对象,而不是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>')
推荐阅读
- javascript - Cookie 的安全性
- android - GridLayoutManager java.lang.ArrayIndexOutOfBoundsException
- reactjs - React Hooks:状态没有在函数中更新
- sqlite - 如何让 SQLAlchemy 从视图而不是表创建类?
- css - 使用视口缩放全宽视频背景行
- php - ModSecurity 和“Northwind”
- python - 接受一个整数 k 的函数,它检查整数列表 l 的列表,返回 l 中整数列表数的计数,总和为 k
- c# - 如何在 Kubernetes 集群中使用 FQDN 连接到 gRPC 服务器?
- edk2 - Edk2 驱动绑定问题
- python - 如何使用 Python 的 docutils 解析像树一样的 RST 文档?