【发布时间】:2014-11-13 14:39:54
【问题描述】:
我是 nodeJS javascript 的新手,这里有一个简单的问题。
我在 javascript 中有一个二叉搜索树 (BST)。每个节点都有一个值和一个计数。我们将单词插入 BST,这样每个节点就代表一个单词。插入时,如果单词已经在 BST 中,我们希望增加该单词的计数,其中 count 是节点上的一个属性。
当我想显示节点及其计数时,我的问题就出现了。显示计数无法正常工作。即BST.prototype.showWords = function(node)不正确。
感谢您的帮助和洞察力!!!
文件:
bstnode.js - '节点类'
BST.js - 二叉搜索树类
wordCount.js - 读入一个文本文件,分割空格以获取单词,并创建节点。我希望每个节点代表一个单词,如果该单词出现多次,则每次在该节点上计数++。
// wordCount.js
var BST = require('./bst.js');
var fs = require('fs');
var countNodes = require('./countNodes.js');
// THIS RIGHT HERE DOES NOT WORK CORRECTLY.
BST.prototype.showWords = function (node) {
if (node !== null) {
this.inOrder(node.left);
console.log(node.showCount());
this.inOrder(node.right);
}
};
// get the file, and get it into an array of string-words
var filePath = './simpleTest.txt';
var contents = fs.readFileSync(filePath).toString();
var stringArr = contents.split(' ');
var myBST = new BST();
for (var i=0; i<stringArr.length; i++){
var word = stringArr[i].trim();
var aNode = myBST.find(word);
console.log(aNode);
if ( aNode !== null ) { // then word exists in BST already,
aNode.count++; // node count ++ on that one
}
else { // then word dne in BST, so add it now!
myBST.insert(word);
}
}
myBST.showWords(myBST.root);
// bstnode.js
'use strict';
var Node = function (data, left, right) {
this.data = data;
this.count = 1;
this.left = left;
this.right = right;
};
Node.prototype.show = function () {
return this.data;
};
Node.prototype.show2 = function () {
return (this.data + ' ' + this.count);
};
module.exports = Node;
'use strict';
// bst.js - has the BST CTor function, and requires the bstnode in
var Node = require('./bstnode');
// BST CTor function
var BST = function() { // Binary Search Tree class
this.root = null;
};
BST.prototype.insert = function (data) {
var n = new Node(data, null, null);
if (this.root === null) {
this.root = n;
} else {
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;
}
}
}
}
};
// inOrder: log VALUES in order starting from node param
BST.prototype.inOrder = function (node) {
if (node !== null) {
this.inOrder(node.left);
console.log(node.show() + " ");
this.inOrder(node.right);
}
};
BST.prototype.find = function (data) {
var current = this.root;
while (current && current.data !== data) {
if (data < current.data) {
current = current.left;
} else {
current = current.right;
}
}
return current;
};
module.exports = BST;
【问题讨论】:
-
"显示计数不能正常工作。" -- “不能正常工作”是什么意思?您想要的结果与实际结果如何?
标签: javascript node.js binary-tree binary-search-tree