[英]BST in javascript using reference objects
I found this algorithm from Data structures and algorithms in javascript. 我从javascript中的数据结构和算法中找到了该算法。 For the insertion method, there are two references to the root (current and parent).
对于插入方法,有两个对根的引用(当前和父)。 My question is, why can't i change both current and parent to this.root?
我的问题是,为什么我不能同时将current和parent更改为this.root? They both point to this.root.
他们俩都指向this.root。 The code does not work properly when I do that however
当我这样做时,代码无法正常工作
'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);
current
does not refer to this.root
throughout the entire algorithm. 在整个算法中,
current
不涉及this.root
。
It is initialized as this.root
, but then it is quickly reassigned to either current = current.left;
它初始化为
this.root
,但随后很快将其重新分配给current = current.left;
this.root
or current = current.right;
或
current = current.right;
. 。 From that moment on
current
is no longer this.root
. 从那一刻起,
current
不再是this.root
。 It is either this.root.left
or this.root.right
. 它是
this.root.left
或this.root.right
。
On the next iteration of the while loop it will get reassigned again, but it will never be this.root
again, since it is alway being reassigned to a child node of current
. 在while循环的下一次迭代中,它将再次被重新分配,但是永远不会再是
this.root
,因为它总是被重新分配给current
的子节点。
parent
is similar, being this.root
only on the first iteration. parent
是类似的,仅在第一次迭代时this.root
。 On each subsequent iteration it is reassigned by parent = current;
在随后的每次迭代中,它都由
parent = current;
重新分配parent = current;
and since current is no longer
this.root ,
parent won't be
this.root` either. 并且由于
current is no longer
this.root ,
父级won't be
this.root`。
parent
仅用于保留上一个节点的参考,创建新节点n
,然后在树中找到它的位置,当current
变为null
,找到节点n
的目标位置,则需要将其分配为child( left
或right
)到parent
节点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.