我想出了一个带有内部子程序的程序,但是我很难找到一个没有单一程序的解决方案,这个关键字让我的事情变得有点复杂。
BinarySearchTree.prototype.countNodes = function () {
var count = 1;
var recurseNodes = function(node) {
if (node.left) {
count++;
recurseNodes(node.left);
}
if (node.right) {
count++;
recurseNodes(node.right);
}
}
recurseNodes(this);
return count;
}
这是实施的其余部分
var BinarySearchTree = function(value){
this.value = value;
this.left = null;
this.right = null;
};
BinarySearchTree.prototype.insert = function(nodeValue) {
if (nodeValue < this.value) {
if (this.left) {
this.left.insert(nodeValue);
} else {
this.left = new BinarySearchTree(nodeValue);
}
} else if (nodeValue > this.value) {
if (this.right) {
this.right.insert(nodeValue);
} else {
this.right = new BinarySearchTree(nodeValue);
}
}
};
答案 0 :(得分:1)
您可以在子节点上递归调用countNodes
方法,因为它们也是BinarySearchTree
的实例。
BinarySearchTree.prototype.countNodes = function () {
var count = 1;
if (node.left)
count += node.left.countNodes();
if (node.right)
count += node.right.countNodes();
return count;
}
通过使用带有节点或BinarySearchTree.countNodes(node)
的静态null
方法,您可以使其更加优雅,但我会将其作为练习留给您。