Javascript 二叉搜索树语法
对于JS中二叉搜索树实现的这一部分,引用“this.\u root”有什么意义?(为什么他们不能说“this.root”)?此链接位于Javascript 二叉搜索树语法,javascript,binary-tree,binary-search-tree,Javascript,Binary Tree,Binary Search Tree,对于JS中二叉搜索树实现的这一部分,引用“this.\u root”有什么意义?(为什么他们不能说“this.root”)?此链接位于 BinarySearchTree.prototype={ //这里有更多代码 移除:函数(值){ var found=false, parent=null, 当前=此根, 儿童计数, 替换 替代父母; //确保有要搜索的节点 while(!found&¤t){ //如果该值小于当前节点的值,则向左移动 如果(值当前值){ 父项=当前; current
BinarySearchTree.prototype={
//这里有更多代码
移除:函数(值){
var found=false,
parent=null,
当前=此根,
儿童计数,
替换
替代父母;
//确保有要搜索的节点
while(!found&¤t){
//如果该值小于当前节点的值,则向左移动
如果(值<当前值){
父项=当前;
current=current.left;
//如果该值大于当前节点的值,请向右移动
}else if(值>当前值){
父项=当前;
current=current.right;
//值相等,找到了!
}否则{
发现=真;
}
}
//仅当找到节点时才继续
如果(找到){
//继续
}
},
//这里有更多代码
};
他们可能试图指示不应在对象之外访问此变量(其他语言中的private
)
Python有一个强大的惯例,即使用以下划线字符开头的名称来指示此字段或方法是私有的。作者可能正试图将相同的约定应用于javascript 我想更完整的例子在这里:
关于
this.\u root
-我认为这只是作者的决定,没有任何特殊意义。谢谢-所以我可以将其解释为-实际上我可以只写“this.root”而不是“this.\u root”,如果我只是实现一个简单的BST,而不担心范围问题如果你在哪里写自己的,是的,这不是问题。如果使用链接到的库,则需要使用他们提供的名称。可能作者认为“_root”与现有属性冲突的可能性较小。JSLint将此称为无意义和糟糕的形式,因为它根本不是真正的隐私…谢谢!我回答了第一个答案,但也听取了您的意见:如果我只是实现一个简单的BST,并且不担心范围问题,那么我可以将其解释为——实际上,我可以只写“this.root”而不是“this.\u root”,这也很清楚,根不是根的单独变量?它只是在原型主体中定义的“根”,在iti之外是不可访问的。我不知道实现细节,但只要你是一致的,你可以调用任何东西(大约有10-20个例外,“根”不是其中之一)。
BinarySearchTree.prototype = {
//more code here
remove: function(value){
var found = false,
parent = null,
current = this._root,
childCount,
replacement,
replacementParent;
//make sure there's a node to search
while(!found && current){
//if the value is less than the current node's, go left
if (value < current.value){
parent = current;
current = current.left;
//if the value is greater than the current node's, go right
} else if (value > current.value){
parent = current;
current = current.right;
//values are equal, found it!
} else {
found = true;
}
}
//only proceed if the node was found
if (found){
//continue
}
},
//more code here
};