使用引用对象的javascript中的BST
我从javascript中的数据结构和算法中找到了这个算法。对于插入方法,有两个对根的引用(当前和父)。我的问题是,为什么我不能将current和parent都更改为this.root?他们都指向这个根。但是,当我这样做时,代码不能正常工作使用引用对象的javascript中的BST,javascript,algorithm,binary-search-tree,Javascript,Algorithm,Binary Search Tree,我从javascript中的数据结构和算法中找到了这个算法。对于插入方法,有两个对根的引用(当前和父)。我的问题是,为什么我不能将current和parent都更改为this.root?他们都指向这个根。但是,当我这样做时,代码不能正常工作 'use strict'; var BST = function() { this.root = null; //embed _Node inside BST so it comes with when BST is created this._
'use strict';
var BST = function() {
this.root = null;
//embed _Node inside BST so it comes with when BST is created
this._Node = function(data, left, right) {
this.data = data;
this.count = 1;
this.left = left;
this.right = right;
};
this._Node.prototype.show = function() {
return this.data;
};
this._Node.prototype.showCount = function() {
return this.count;
}
};
BST.prototype.insert = function(data) {
//use this data for a new node
var n = new this._Node(data, null, null);
//if root is null, put this new node and its data into root
if (this.root === null) {
this.root = n;
}
else {
//find a child position for this node
var current = this.root;
var parent;
while (true) {
parent = current;
if (data < current.data) {
current = current.left;
if (current === null) {
parent.left = n;
break;
}
}
else {
current = current.right;
if (current === null) {
parent.right = n;
break;
}
}
}
}
};
var nums = new BST();
nums.insert(23);
nums.insert(45);
nums.insert(16);
nums.insert(37);
nums.insert(3);
nums.insert(99);
nums.insert(22);
“严格使用”;
var BST=函数(){
this.root=null;
//在BST中嵌入_节点,以便在创建BST时使用
此._节点=函数(数据,左,右){
这个数据=数据;
这个.count=1;
this.left=左;
这个。右=右;
};
此._Node.prototype.show=函数(){
返回此.data;
};
这是。_Node.prototype.showCount=函数(){
返回这个.count;
}
};
BST.prototype.insert=函数(数据){
//将此数据用于新节点
var n=新的this.\u节点(数据,null,null);
//如果root为null,则将此新节点及其数据放入root
if(this.root==null){
this.root=n;
}
否则{
//查找此节点的子位置
var current=this.root;
var父代;
while(true){
父项=当前;
if(数据<当前数据){
current=current.left;
如果(当前===null){
parent.left=n;
打破
}
}
否则{
current=current.right;
如果(当前===null){
parent.right=n;
打破
}
}
}
}
};
var nums=new BST();
插入数字(23);
插入数字(45);
插入数字(16);
插入数字(37);
插入数字(3);
插入数字(99);
插入数字(22);
current
在整个算法中不引用此.root
它被初始化为this.root
,但随后它被快速重新分配到current=current.left代码>或<代码>当前=当前。右侧代码>。从那一刻起,当前的不再是这个.root
。它是this.root.left
或this.root.right
在while循环的下一次迭代中,它将再次被重新分配,但它永远不会再是this.root
,因为它总是被重新分配给current
的子节点
parent
类似,仅在第一次迭代时this.root
。在随后的每次迭代中,它由parent=current重新分配因为当前不再是这个.根,
父也不再是这个.根`了。父只是用来保存前一个节点的引用,你创建新的节点n
,然后在树中找到它的位置,一旦当前变成空,您已找到节点n
的目标位置,需要将其作为子节点(left
或right
)分配给父节点