[英]accessing a property of a node, javascript binary search tree
我是nodeJS javascript的新手,這里有一個簡單的問題。
我在javascript中有一個二進制搜索樹(BST)。 每個節點都有一個值和一個計數。 我們在BST中插入單詞,以便每個Node代表一個單詞。 插入后,如果單詞已經在BST中,我們想增加該單詞的計數,其中count是Node上的一個屬性。
我想顯示節點及其數量時遇到問題。 顯示計數無法正常工作。 也就是說,BST.prototype.showWords =函數(節點)不正確。
謝謝您的幫助和見識!!! 文件:
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;
一個朋友幫了我的忙
// THIS RIGHT HERE -- - --
// That's because it should call itself recursively, not the inOrder function!
BST.prototype.showWords = function (node) {
if (node !== null) {
this.showWords(node.left);
console.log(node.showCount());
this.showWords(node.right);
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.