二叉树的删除为什么一定要返回更新后的子节点?-灵析社区

周舟莫UI设计

二叉树的删除为什么一定要返回更新后的子节点 ... //二叉树的删除 remove(key) { this.removeNode(this.root, key) } removeNode(node, key) { if (node == null) { return null } if (this.compareFn(key, node.key) === Compare.less) { //本人疑惑的地方//tip2 this.removeNode(node.left, key) } else if (this.compareFn(key, node.key) === Compare.bigger) { this.removeNode(node.right, key) } else { //tip1 node = null } } } var mytree = new BST() mytree.insert(4) mytree.insert(5) mytree.insert(1) mytree.remove(1) 我看到大家都是以下这么写二叉树的删除的,不明白的是我在tip2处将node.left传入removeNode函数之后,按照JavaScript复杂数据类型变量存的是栈中的地址,那么我在tip1处将key为1的这个节点赋值为null,也就是mytree.root.left这个节点赋值为Null之后,为什么它最终没有被赋值为null,而是要采用下面tip3的方式才能实现删除呢 removeNode(node,key){ if(node==null){ return null } if(this.compareFn(key,node.key)===Compare.less){ //都采用了赋值的方式,把更新后的子节点赋值给父节点要修改的地方 //tip3 node.left = this.removeNode(node.left,key) return node }else if(this.compareFn(key,node.key)===Compare.bigger){... 1.以下是比较官方的写法 const Compare = { less:-1, bigger:1, equ:0 } class Node{ constructor(key){ this.key = key this.left = null this.right = null } } class BST { constructor(){ this.root = null } insert(key){ if(this.root==null){ this.root = new Node(key) }else{ this.insertNode(this.root,key) } } compareFn(a,b){ if(a===b){ return Compare.equ } return a

阅读量:14

点赞量:0

问AI
"截屏2023-12-16 17.00.06.png" (https://wmlx-new-image.oss-cn-shanghai.aliyuncs.com/images/20241030/c52067ca3e6884ce37ef2729ef8d99d3.png) 先看上面这段代码你能理解为什么"node"没有被赋值为"null"吗?当你把这个"node"传给一个函数的时候并且在函数内部对传入的参数做修改的话你想想是不是等同于上面这样; 的确引用类型存储的是指针,但是你对变量的赋值修改的是指针的指向,并不会修改另一个变量的指针 "截屏2023-12-16 17.12.23.png" (https://wmlx-new-image.oss-cn-shanghai.aliyuncs.com/images/20241030/145889cb78922a667819727d5cef09cb.png)