BST中的计数节点通过Javascript实现了伪节点补充countNodes而没有内部子例程

时间:2015-10-15 01:56:38

标签: javascript

我想出了一个带有内部子程序的程序,但是我很难找到一个没有单一程序的解决方案,这个关键字让我的事情变得有点复杂。

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);
    }
  }
};

1 个答案:

答案 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方法,您可以使其更加优雅,但我会将其作为练习留给您。

相关问题